Isomorphic Strings — LeetCode 205 Python Solution
- Problem
- #205
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t.
Python solution
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
d1 = {}
d2 = {}
for a, b in zip(s, t):
if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
return False
d1[a] = b
d2[b] = a
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 205. Isomorphic Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 205. Isomorphic Strings?
- LeetCode 205. Isomorphic Strings is rated Easy on LeetCode.
- What is the time complexity of LeetCode 205. Isomorphic Strings?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 205. Isomorphic Strings?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 205. Isomorphic Strings cover?
- LeetCode 205. Isomorphic Strings is tagged Hash Table and String on LeetCode.