0:00 / 0:00

Can each letter of s turn into one letter of t, with no two sharing? A two-way codebook settles it in a single pass.

▼

The problem

LeetCode 205 (Easy). Given two strings s and t of the same length, return true if they are isomorphic: the characters of s can be replaced to get t, every occurrence of a character is replaced by the same character, and no two characters map to the same character (a character may map to itself).

Examples (LeetCode's three, plus one that fails only in reverse): ("egg", "add") → true (e → a, g → d; walked through in scene 5), ("foo", "bar") → false (o would need to be both a and r), ("paper", "title") → true (p → t, a → i, e → l, r → e) and ("badc", "baba") → false: every letter of s does give one letter of t (b → b, a → a, d → b, c → a), so a forward map alone accepts it, but b and d would both become b; the reverse map catches it at position 2 (scene 5).

TRY IT ON LEETCODE ▶

The solution

def isIsomorphic(s, t):
    s2t, t2s = {}, {}
    for a, b in zip(s, t):
        if s2t.get(a, b) != b or t2s.get(b, a) != a:
            return False
        s2t[a] = b
        t2s[b] = a
    return True

Transcript

Isomorphic Strings. You get two strings of the same length, s and t. Can you turn s into t by swapping letters? Each letter must always become the same letter, and no two letters may become the same one.

Egg and add works: E becomes A, G becomes D. True. Foo and bar fails: O would have to become both A and R. False. Paper and title works too. But B A D C against B A B A fails: B and D would both become B.

One slow way checks every pair of positions. Two letters of s must match exactly when the letters below them match. Five letters make twenty-five pairs. That's n squared.

Better: one pass, with a codebook that works both ways. The left page maps each letter of s to t. The right page maps each letter of t back to s. At each position, look up both. If the s letter is written down, it must give this t letter. If the t letter is written down, it must point back. If both are new, write both entries.

Decode egg into add. E is new: write E to A, and A back to E. G to D, D back to G. The second G: the book says D, and D points back to G. No clash, so it's true. Now B A D C against B A B A. B and A map to themselves. Then D wants B. The left page has no D, so a forward map alone would say yes. But the right page says B belongs to B. Clash. False.

In code: two dictionaries and one loop. If either lookup disagrees, return false. A missing letter defaults to a match, so new letters pass. Otherwise, record both. If the loop finishes, return true.

Each position costs two lookups and two writes, so time is order n. The pages hold one entry per character of a fixed alphabet, so space is constant.

Map forward, map back, stop at the first clash. That's Isomorphic Strings.