Isomorphic Strings

Easy

Topics
Hash TableString

Given two strings s and t, return true if they are isomorphic — the characters in s can be replaced to get t with a consistent one-to-one mapping (no two characters map to the same character).

Example 1

segg
tadd
A consistent one-to-one letter mapping exists, so the answer is true. Both directions have to be checked: a single map would wrongly accept two different letters mapping onto the same one.
The two strings aligned column by column.
Input:  s = "egg", t = "add"
Output: true

Example 2

sfoo
tbar
The shaded column breaks the mapping — some letter would need two different images, or two letters would collide on one. So the answer is false.
Input:  s = "foo", t = "bar"
Output: false

Example 3

spaper
ttitle
Input:  s = "paper", t = "title"
Output: true

Constraints

  • 1 <= s.length <= 5*10^4
  • t.length == s.length
  • s and t consist of any valid ASCII characters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Isomorphic means there is a consistent one-to-one renaming of characters taking s to t. Two conditions, and missing either is the usual bug:

  • each character of s maps to exactly one character of t, and
  • no two distinct characters of s map to the same character of t.

A single map enforces only the first. "badc" to "baba" passes a one-way check — d and c both map to a without contradicting anything already recorded — but is not a bijection. So two maps are needed, one in each direction, and both must stay consistent.

The alternative is to compare first-occurrence patterns: rewrite each string as the index at which each character first appeared, and compare those sequences. "egg" and "add" both become [0,1,1]. It is the same idea with the bijection built into the encoding.

Approach

  1. Reject unequal lengths.
  2. Walk both strings together, maintaining s_to_t and t_to_s.
  3. If either map already holds a conflicting entry, return false; otherwise record both.

Dry Run

s = "egg", t = "add"
 (e,a)  neither mapped -> s2t{e:a}  t2s{a:e}
 (g,d)  neither mapped -> s2t{e:a,g:d}  t2s{a:e,d:g}
 (g,d)  s2t[g]==d ✓ and t2s[d]==g ✓
 true

s = "foo", t = "bar"
 (f,b)  ok
 (o,a)  ok
 (o,r)  s2t[o] is 'a', not 'r'  -> false

s = "badc", t = "baba"       the case a single map gets wrong
 (b,b) ok   (a,a) ok
 (d,b)  s2t has no d, but t2s[b] is already 'b', not 'd'  -> false

Complexity

  • Time — O(n): one pass, constant-time map operations.
  • Space — O(1): the two maps hold at most one entry per distinct character, and the alphabet is bounded — ASCII here, so at most 128 entries each regardless of the 5*10^4 input length. Calling that O(1) is the fixed-alphabet convention and is worth stating explicitly rather than leaving it to look like O(n).

Common Pitfalls

  • Using one map instead of two. "badc" / "baba" is the counterexample, and it is the single most common failure on this problem.
  • Skipping the length check. Unequal lengths can otherwise pass if the shorter is a consistent prefix.
  • Comparing sets of distinct characters, or character counts. "aab" and "abb" have matching count multisets and are not isomorphic.
  • Assuming lowercase letters. The constraints say any valid ASCII, so a fixed 26-slot array is too small; 128 or a hash map.

Full Solution — all languages

class Solution:
    def isIsomorphic(self, s, t):
        if len(s) != len(t):
            return False
        st, ts = {}, {}
        for a, b in zip(s, t):
            if a in st and st[a] != b:
                return False
            if b in ts and ts[b] != a:
                return False
            st[a] = b
            ts[b] = a
        return True
SensAI
Beta
Tap the mic to stop voice mode