Skip to main content

28. Isomorphic Strings

easyAsked at Ola

Decide whether two strings have a one-to-one character mapping.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t, preserving order and using a one-to-one mapping.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s.length == t.length
  • s and t consist of any valid ASCII characters

Examples

Example 1

Input
s = "egg", t = "add"
Output
true

Example 2

Input
s = "foo", t = "bar"
Output
false

Approaches

1. Pattern signature

Convert each string into a normalized index pattern and compare.

Time
O(n)
Space
O(n)
const sig = x => { const m = new Map(); return [...x].map(c => { if (!m.has(c)) m.set(c, m.size); return m.get(c); }).join(','); };
return sig(s) === sig(t);

Tradeoff:

2. Two-way map

Maintain forward and reverse character maps; reject any mismatch on either.

Time
O(n)
Space
O(n)
function isIsomorphic(s, t) {
  const ab = new Map(), ba = new Map();
  for (let i = 0; i < s.length; i++) {
    const a = s[i], b = t[i];
    if (ab.has(a) && ab.get(a) !== b) return false;
    if (ba.has(b) && ba.get(b) !== a) return false;
    ab.set(a, b); ba.set(b, a);
  }
  return true;
}

Tradeoff:

Ola-specific tips

Ola interviewers care that you guard both directions of the mapping; tie it to validating that a region-code rename in two configs stays bijective.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Isomorphic Strings and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →