Isomorphic Strings

Two strings are isomorphic iff there is a bijection between their characters preserving order.

Easy
Time O(N) Space O(1)
LeetCode
4 min read
hash-map strings

Problem#

Given two strings s and t, return true iff a bijective mapping exists between s’s characters and t’s characters that preserves order — i.e., f(s[i]) = t[i] for all i and f is one-to-one.

Examples#

  • s = "egg", t = "add"true (e->a, g->d).
  • s = "foo", t = "bar"false (o would map to both a and r).
  • s = "paper", t = "title"true.

Constraints#

  • 1 <= s.length <= 5 * 10^4, ASCII characters.

Hints#

Hint
Track both directions: s[i] -> t[i] and t[i] -> s[i]. A conflict on either side is failure.

Approach#

Two parallel maps (or int[256] arrays). On each index check existing mapping; mismatch returns false. If neither side is mapped, assign both.

Solution#

Isomorphic Strings
class Solution {
public:
bool isIsomorphic(string s, string t) {
if (s.size() != t.size()) return false;
int s2t[256] = {0}, t2s[256] = {0};
for (int i = 0; i < (int)s.size(); ++i) {
unsigned char a = s[i], b = t[i];
if (s2t[a] == 0 && t2s[b] == 0) {
s2t[a] = b;
t2s[b] = a;
} else if (s2t[a] != b || t2s[b] != a) {
return false;
}
}
return true;
}
};

Editorial#

Both-direction tracking is essential — a single-direction map would accept "ab" -> "aa" (a maps to a, b maps to a, but a would already be the image of a). The arrays default-zero is fine here because all valid ASCII characters are >= 1; if zero could be a real value, use sentinel -1 instead.

Complexity#

  • Time: O(N).
  • Space: O(1) — fixed 256-byte arrays.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.