#205
Isomorphic Strings
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use two hash maps to track the mappings from characters in s to t and from t to s. This way, we ensure that each character maps uniquely and consistently.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two hash maps: one for mapping characters from s to t and another for t to s.
- 2Step 2: Iterate through the characters of both strings simultaneously.
- 3Step 3: For each character pair, check if the current character from s is already mapped to a different character in t or vice versa. If so, return false.
- 4Step 4: If the mappings are valid, update the hash maps.
- 5Step 5: If the loop completes without conflicts, return true.
solution.py12 lines
1# Full working Python code
2
3def isIsomorphic(s, t):
4 map_s_to_t = {}
5 map_t_to_s = {}
6 for char_s, char_t in zip(s, t):
7 if (char_s in map_s_to_t and map_s_to_t[char_s] != char_t) or
8 (char_t in map_t_to_s and map_t_to_s[char_t] != char_s):
9 return False
10 map_s_to_t[char_s] = char_t
11 map_t_to_s[char_t] = char_s
12 return Trueℹ
Complexity note: The time complexity is linear because we only traverse the strings once. The space complexity is also linear due to the hash maps storing the mappings.
- 1Isomorphic strings require a one-to-one mapping between characters.
- 2Using hash maps allows efficient checking and updating of character mappings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.