Member-only story

Leetcode 205. Isomorphic Strings

Daniel Mesizah
2 min readJul 13, 2021

--

QUESTION:

CODE SOLUTION:

class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_dict = {}
t_dict = {}

if len(s) != len(t):
return False

for i in range(len(s)):
if s[i] not in s_dict:
s_dict[s[i]] = t[i]

if t[i] not in t_dict:
t_dict[t[i]] = s[i]
if s_dict[s[i]] != t[i] or t_dict[t[i]] != s[i]:
return False

return True
Time Complexity: O(N)
Space Compexity: O(1)

EXPLAINATION:

INPUT:

s = egg

t = add

So what happened?

We declared 2 dictionaries, s_dict and t_dict

If s and t have different word length, then it is not isomorphic

What happened inside the for loop (we used s length because we know s and t have same length). In this case, the loop will run 3 times because s length is 3.

1st iteration:

since both s_dict and t_dict are empty, after 1st iteration, we have:

--

--

Daniel Mesizah
Daniel Mesizah

Written by Daniel Mesizah

Coder who likes to share what he knows with the rest of the world

No responses yet