InterviewPrepKit

Home / Coding / Arrays & Hashing

Isomorphic Strings

easy Original β†—
Solving tips
  • Recognize this as building a bijection in one pass: walk s and t in lockstep and commit each character's mapping on its first appearance.
  • There are two independent failure modes, so keep two maps: s->t catches one source mapping to two targets, and t->s catches two sources colliding on one target (injectivity).
  • Target O(n) time and O(k) space for the alphabet; a terse alternative is len(set(zip(s,t))) == len(set(s)) == len(set(t)).
  • Pitfall: checking only one direction wrongly accepts cases like 'badc'/'baba'; the reverse map (or the distinct-pair count) is mandatory.

Problem

Two strings s and t of equal length are isomorphic if there is a one-to-one substitution of characters that turns s into t: every occurrence of a character in s must map to the same character in t, and no two different characters of s may map to the same character of t. A character may map to itself.

Given s and t, return True if they are isomorphic and False otherwise.

Examples

  • s = "egg", t = "add" β†’ True β€” map e β†’ a, g β†’ d; the mapping is consistent and injective.
  • s = "foo", t = "bar" β†’ False β€” o would have to map to both a and r.
  • s = "badc", t = "baba" β†’ False β€” b β†’ b and d β†’ b would send two different characters to b, which the one-to-one rule forbids.

Constraints

  • 1 <= len(s) <= 5 * 10^4
  • t has the same length as s
  • The strings may contain any valid ASCII characters.

Length 5 * 10^4 makes comparing all pairs of positions (O(n^2)) too slow; a single hashed pass is expected.

Think about it first

Hint 1 Walk both strings in lockstep and try to build the substitution as you go. What are the two distinct ways a new pair (s[i], t[i]) can contradict what you've already committed to?
Hint 2 One dictionary from s-characters to t-characters catches "same source, two targets". What extra structure catches "two sources, same target"?
Hint 3 Keep two hash maps — s→t and t→s. For each position, if either map already binds the character to something different, fail; otherwise record both directions. Consistency in both maps at the end means isomorphic.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.