Isomorphic Strings: Leetcode

Ekta Dhobley
2 min readJan 4, 2023

--

Question

Question explanation: Two strings are isomorphic if all occurrences of a character in one string can be replaced by another character in another string while preserving the order of characters.

Conceptual explanation: Here, we will use a dictionary or a hashmap, in order to check if both strings are isomorphic. It is as simple as it sounds, we will process each character in the string (say string s) exactly once, and map it to the corresponding character in string t. And while going through the hashmap/dictionary we find that the correct characters are not mapped to each other, we will simply return False.

Python Code:

class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:

if len(s) != len(t): #if the lengths are unequal we return false
return False

hashmap = {}
for i in range(len(s)):
if s[i] not in hashmap:
if t[i] in hashmap.values(): #if s[i] is in the map but t[i] is not we return False
return False
hashmap[s[i]] = t[i] #map the corresponding characters to each other
elif hashmap[s[i]] != t[i]: #if s[i] is in the map, but it is not mapped correctly, we return False
return False
return True

Time Complexity: O(N) since we are traversing through both strings exactly once.

Space Complexity: O(N), since we are using a hashmap.

Thanks for reading. :)

--

--

Ekta Dhobley

Software Engineer at Goldman Sachs NYC. MS Computer Science from Rutgers University, New Brunswick. I like to pen down my learnings.