Isomorphic Strings

Easyhash-tablestring
Category: Array & Hashing
Companies that ask this question:
AmazonLinkedInGoogle

Approach

Isomorphic Strings

Approach

Use two hash maps to track bidirectional character mappings between strings.

Algorithm

  1. Check if strings have same length
  2. Create two maps: s→t and t→s
  3. For each character pair (cs, ct):
    • If cs already mapped, verify it maps to ct
    • If ct already mapped, verify it maps to cs
    • Add new mappings if not exist
  4. Return true if all checks pass

Complexity

  • Time: O(n) - single pass through strings
  • Space: O(1) - at most 256 ASCII characters

Key Insights

  • Need bidirectional mapping to prevent collisions
  • Example: "foo" and "bar" would fail without reverse mapping
  • Each character must map to exactly one other character

Solution

java
1class Solution {
2    public boolean isIsomorphic(String s, String t) {
3        if (s.length() != t.length()) return false;
4        
5        Map<Character, Character> mapS = new HashMap<>();
6        Map<Character, Character> mapT = new HashMap<>();
7        
8        for (int i = 0; i < s.length(); i++) {
9            char cs = s.charAt(i);
10            char ct = t.charAt(i);
11            
12            if (mapS.containsKey(cs)) {
13                if (mapS.get(cs) != ct) return false;
14            } else {
15                mapS.put(cs, ct);
16            }
17            
18            if (mapT.containsKey(ct)) {
19                if (mapT.get(ct) != cs) return false;
20            } else {
21                mapT.put(ct, cs);
22            }
23        }
24        
25        return true;
26    }
27}
Loading visualizer...