LeetCode 205: Isomorphic Strings is an Easy hashmap problem. This Python walkthrough develops a bidirectional mapping solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Hashmap |
| Reusable pattern | bidirectional mapping |
| Complexity | O(n) time and O(k) space |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, maintain mappings in both directions so each character corresponds to exactly one partner and no two source characters share a target. The invariant worth writing beside the code is: Both maps describe a one-to-one correspondence for every processed character pair.
Step-by-step algorithm
- Identify the input state consumed by
isIsomorphic(s, t)and initialize the data required by the bidirectional mapping pattern. - Maintain mappings in both directions so each character corresponds to exactly one partner and no two source characters share a target.
- After each update, verify the page’s central invariant: Both maps describe a one-to-one correspondence for every processed character pair.
- Finish only after the boundary behavior is covered: Length mismatch fails; repeated patterns must match in both strings.
Python solution
class Solution:
def isIsomorphic(self, s, t):
if len(s) != len(t): return False
forward, backward = {}, {}
for a, b in zip(s, t):
if (a in forward and forward[a] != b) or (b in backward and backward[b] != a): return False
forward[a], backward[b] = b, a
return TrueReading the implementation
The main entry point is isIsomorphic(s, t). The named working state includes forward; those variables make the bidirectional mapping state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, maintain mappings in both directions so each character corresponds to exactly one partner and no two source characters share a target.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Maintain mappings in both directions so each character corresponds to exactly one partner and no two source characters share a target. Each update records the current item without invalidating earlier decisions; consequently, both maps describe a one-to-one correspondence for every processed character pair.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().isIsomorphic("egg","add")Common mistakes and edge cases
- Problem-specific boundary: Length mismatch fails; repeated patterns must match in both strings.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that both maps describe a one-to-one correspondence for every processed character pair.
Interview review checklist
- Explain why bidirectional mapping matches the structure of this input.
- State the invariant in one sentence before tracing code: Both maps describe a one-to-one correspondence for every processed character pair.
- Derive O(n) time and O(k) space from how many times each element or state is visited.
- Test the boundary explicitly: Length mismatch fails; repeated patterns must match in both strings.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 383. Ransom Note · Next: 290. Word Pattern