CodingNodes / Arrays & Hashing / Isomorphic Strings System design Space play · ←→ step · R restart

Problem

Two strings s and t are isomorphic if you can rename the letters of s to get exactly t.

The renaming must be consistent: every occurrence of a letter changes to the same new letter, and two different letters never change to the same one. A letter may map to itself. Return true or false.

Constraints

  • 1 ≤ s.length ≤ 5 · 10⁴
  • t.length may differ from s.length
  • s and t use ASCII characters

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(min(n, alphabet))

Time: One pass over the strings with O(1) map lookups at each index.

Space: Each map holds at most one entry per distinct letter, bounded by the alphabet size.

Keep a map from s-letters to t-letters and another from t-letters back to s-letters. At each index, both maps must agree with the current pair. Checking only one direction would let two letters share a target.