Isomorphic Strings

EasyHash Tables · Bijection🧩 Hashing & CountingLeetCode #205 ↗Updated

Problem

Two equal-length strings s and t are isomorphic if you can rename the characters of s to obtain t, where each character is always renamed the same way and no two different characters receive the same new name (a character may map to itself). Return whether s and t are isomorphic.
Inputs="egg", t="add"Outputtrue
Inputs="foo", t="bar"Outputfalse
Inputs="badc", t="baba"Outputfalse

1 ≤ n ≤ 5·104  ·  t.length == s.length  ·  any valid ASCII characters

Try it yourself

Java
class Solution {
    public boolean isIsomorphic(String s, String t) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The mapping must be a bijection: check consistency in both directions (s→t and t→s). Equivalently, at every index the two characters must have been last seen at the same position.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceCompare Every Pair of Indices

Time O(n2)Space O(1)

A valid renaming exists iff for every pair i < j, s[i]==s[j] exactly when t[i]==t[j]. Check all pairs; any mismatch means one char maps to two, or two chars map to one.

Java
public boolean isIsomorphic(String s, String t) {
    if (s.length() != t.length()) return false;
    for (int i = 0; i < s.length(); i++) {
        for (int j = 0; j < i; j++) {
            boolean sameS = s.charAt(i) == s.charAt(j);
            boolean sameT = t.charAt(i) == t.charAt(j);
            if (sameS != sameT) return false;
        }
    }
    return true;
}

No extra memory and easy to argue, but quadratic.

At a glance

LevelApproachTimeSpace
Brute ForceCompare Every Pair of IndicesO(n2)O(1)
BetterTwo Hash Maps (s→t and t→s)O(n)O(k)
OptimalLast-Seen Index ArraysO(n)O(1)
Common pitfalls
  • Checking only s→t: "ab"/"aa" would wrongly pass.
  • Storing i instead of i+1 — index 0 is confused with “unseen”.
  • Sizing arrays to 26 — the input can be any ASCII character, not just lowercase.
Interview tips
  • Say the word bijection early: one-to-one in both directions.
  • Test "badc"/"baba": each one-way map looks fine, the reverse catches it.
  • Note the trick generalises to Word Pattern (290) by mapping words instead of chars.
Pattern
Two-way character mapping → verify a consistent one-to-one renaming between sequences.
My notes saved in this browser