LeetCode #205 Easy

Isomorphic Strings

Isomorphic Strings is LeetCode 205 (Easy). Given two strings s and t of the same length, return true if they are isomorphic.

  • They are isomorphic if the characters of s can be replaced to get t.
  • Every copy of a character must be replaced by the same character, and the order stays the same.
  • No two different characters may turn into the same character, but a character may turn into itself.
  • The strings can hold any ASCII character, not only lowercase letters.
Constraints
  • 1 <= s.length <= 5 * 10⁴
  • t.length == s.length
  • s and t consist of any valid ascii character.
stringhash-mapbijection
Open on LeetCode ↗
02

Intuition

Line the strings up and read them as pairs of characters at the same index. They are isomorphic exactly when no two pairs contradict each other, in either direction:

  • s to t: a character of s always sits above the same character of t.
  • t to s: a character of t always sits below the same character of s.

So keep one map per direction and test every pair against both. The second map is the part people skip. One map only stops a character of s from having two partners; it does nothing to stop two characters of s from sharing one partner in t.

How to spot this pattern

"Replace every copy of a character the same way, with no two characters sharing a replacement" describes a one-to-one mapping. Comparing two strings this way, or a pattern against a list of words, needs a map in each direction.

03

Approach

Try it first

Before reading on, write the strings "paper" and "title" one above the other and list the pairs of characters in each column. What would a pair that breaks the rule look like? Then find a pair of strings where every character of s has one partner, yet the answer is still false.

1

Keep a map for each direction

s_to_t[a] holds the partner chosen for character a of s, and t_to_s[b] the partner chosen for character b of t. Both start empty, and every pair is written into both, so the two maps always mirror each other.

2

Test each pair against both maps

Walk the strings together. For the pair a, b, s_to_t.get(a, b) gives back b when a has no partner yet, so the test fails only when a already has a different partner. The same test on t_to_s fails when b is already taken by another character. Either failure returns false.

3

Record the pair

If both tests pass, store a → b and b → a. For a pair seen before, this writes the same values again, which is harmless and saves a separate branch.

4

Return true after the last index

Reaching the end means every index agreed with both maps. The pairs then rename s into t one character at a time, with each character used by exactly one partner.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isIsomorphic(self, s: str, t: str) -> bool:
▶3 s_to_t, t_to_s = {}, {}
▶4 for a, b in zip(s, t):
▶5 if s_to_t.get(a, b) != b or t_to_s.get(b, a) != a:
▶6 return False
▶7 s_to_t[a] = b
▶8 t_to_s[b] = a
▶9 return True
stptaiptelres → temptyt → semptyboth maps start empty
s"paper"
t"title"
Letters at the same index must be partners. s → t records which letter of t each letter of s turns into, and t → s records the reverse, so a partner can never be shared.
stptaiptelreis → tptt → stpnew pair p ↔ t → record both ways
s[0]p
t[0]t
pairs1
Neither p nor t has a partner yet, so pair them in both maps. From now on, wherever p appears in s, t must appear below it in t, and the other way round.
stptaiptelreis → tptait → stpianew pair a ↔ i → record both ways
s[1]a
t[1]i
pairs2
Neither a nor i has a partner yet, so pair them in both maps. From now on, wherever a appears in s, i must appear below it in t, and the other way round.
stptaiptelreis → tptait → stpiap ↔ t again → agrees
s[2]p
t[2]t
pairs2
p and t were paired earlier, and they meet again at index 2. Both maps agree, so nothing changes.
stptaiptelreis → tptaielt → stpialenew pair e ↔ l → record both ways
s[3]e
t[3]l
pairs3
Neither e nor l has a partner yet, so pair them in both maps. From now on, wherever e appears in s, l must appear below it in t, and the other way round.
stptaiptelreis → tptaielret → stpialeernew pair r ↔ e → record both ways
s[4]r
t[4]e
pairs4
Neither r nor e has a partner yet, so pair them in both maps. From now on, wherever r appears in s, e must appear below it in t, and the other way round.
stptaiptelres → tptaielret → stpialeerevery column agrees → return true
pairs4
resulttrue
Every index matched its pair in both maps. The 4 pairs rename s into t letter by letter, and reading the t → s map renames t back into s. The strings are isomorphic.
05

Common pitfalls

Checking only the s to t direction

✗ Wrong
for a, b in zip(s, t):
    if s_to_t.get(a, b) != b:
        return False
    s_to_t[a] = b
✓ Right
for a, b in zip(s, t):
    if s_to_t.get(a, b) != b or t_to_s.get(b, a) != a:
        return False
    s_to_t[a] = b
    t_to_s[b] = a

For s = "badc", t = "baba" every character of s is new when it first appears, so this returns true. But b and d would both turn into b, which the rules forbid; the answer is false.

Comparing only the number of distinct characters

✗ Wrong
return len(set(s)) == len(set(t))
✓ Right
return len(set(zip(s, t))) == len(set(s)) == len(set(t))

"aab" and "abb" both have two distinct characters, but the first a pairs with a and the second with b. The counts say nothing about where each character sits.

06

Edge cases

Characters other than letters, such as spaces or digits

A dictionary accepts any character. If you swap the maps for arrays, size them for all 128 ASCII codes; an array of 26 indexed by ord(c) - ord('a') breaks on " ".

07

Complexity

Time
O(n)
Space
O(1)
n is the length of the strings. Each index costs a few constant-time map lookups, and each map holds at most 128 entries, one per ASCII character, however long the strings are.
08

Isomorphic Strings FAQ

Is there a one-line check?

Yes: len(set(zip(s, t))) == len(set(s)) == len(set(t)). If there are as many distinct pairs as distinct characters of s, no character of s appears in two different pairs. If there are also as many as distinct characters of t, no character of t does either. Together that is the one-to-one rule.

If s is isomorphic to t, is t isomorphic to s?

Always. A one-to-one renaming of s into t can be read backwards to rename t into s. That is a quick way to see why one map is not enough: a one-way check would give different answers for (s, t) and (t, s).

How is this different from Word Pattern?

Word Pattern (LeetCode 290) asks the same question with a pattern of letters on one side and the words of a sentence on the other. Split the sentence into words, check that there are as many words as letters, then use the same two maps.