InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Isomorphic Strings

easy Original ↗ 00:00

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"Falseo would have to map to both a and r.
  • s = "badc", t = "baba"Falseb → 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug