Skip to main content

12. Isomorphic Strings

easyAsked at N26

Decide whether two strings are isomorphic - characters in one map one-to-one to characters in the other. N26 uses this as a stand-in for column-mapping checks in their KYC field normalization pipeline.

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

Problem

Given two strings s and t, return true if they are isomorphic. Two strings are isomorphic if characters in s can be replaced to get t while preserving order and never mapping two characters to the same one.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • t.length == s.length
  • Strings 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. Single map naive

Map each char in s to t but forget to check the reverse direction.

Time
O(n)
Space
O(1)
const m = new Map();
for (let i=0;i<s.length;i++) {
  if (m.has(s[i]) && m.get(s[i])!==t[i]) return false;
  m.set(s[i], t[i]);
}
return true; // wrong on s="ab", t="aa"

Tradeoff:

2. Two-way mapping

Track s->t and t->s simultaneously; any collision in either direction breaks isomorphism.

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

Tradeoff:

N26-specific tips

N26 wants you to articulate the bijection requirement out loud, since their KYC field-mapper rejects any rule where two source columns collapse onto the same canonical attribute.

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 N26 interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →