Isomorphic Strings
Easy
Topics
Given two strings s and t, return true if they are isomorphic — the characters in s can be replaced to get t with a consistent one-to-one mapping (no two characters map to the same character).
Example 1
true. Both directions have to be checked: a single map would wrongly accept two different letters mapping onto the same one.Input: s = "egg", t = "add" Output: true
Example 2
false.Input: s = "foo", t = "bar" Output: false
Example 3
Input: s = "paper", t = "title" Output: true
Constraints
- 1 <= s.length <= 5*10^4
- t.length == s.length
- s and t consist of any valid ASCII characters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Isomorphic means there is a consistent one-to-one renaming of characters taking s to t. Two conditions, and missing either is the usual bug:
- each character of
smaps to exactly one character oft, and - no two distinct characters of
smap to the same character oft.
A single map enforces only the first. "badc" to "baba" passes a one-way check — d and c both map to a without contradicting anything already recorded — but is not a bijection. So two maps are needed, one in each direction, and both must stay consistent.
The alternative is to compare first-occurrence patterns: rewrite each string as the index at which each character first appeared, and compare those sequences. "egg" and "add" both become [0,1,1]. It is the same idea with the bijection built into the encoding.
Approach
- Reject unequal lengths.
- Walk both strings together, maintaining
s_to_tandt_to_s. - If either map already holds a conflicting entry, return false; otherwise record both.
Dry Run
s = "egg", t = "add"
(e,a) neither mapped -> s2t{e:a} t2s{a:e}
(g,d) neither mapped -> s2t{e:a,g:d} t2s{a:e,d:g}
(g,d) s2t[g]==d ✓ and t2s[d]==g ✓
true
s = "foo", t = "bar"
(f,b) ok
(o,a) ok
(o,r) s2t[o] is 'a', not 'r' -> false
s = "badc", t = "baba" the case a single map gets wrong
(b,b) ok (a,a) ok
(d,b) s2t has no d, but t2s[b] is already 'b', not 'd' -> falseComplexity
- Time — O(n): one pass, constant-time map operations.
- Space — O(1): the two maps hold at most one entry per distinct character, and the alphabet is bounded — ASCII here, so at most 128 entries each regardless of the 5*10^4 input length. Calling that O(1) is the fixed-alphabet convention and is worth stating explicitly rather than leaving it to look like O(n).
Common Pitfalls
- Using one map instead of two.
"badc"/"baba"is the counterexample, and it is the single most common failure on this problem. - Skipping the length check. Unequal lengths can otherwise pass if the shorter is a consistent prefix.
- Comparing sets of distinct characters, or character counts.
"aab"and"abb"have matching count multisets and are not isomorphic. - Assuming lowercase letters. The constraints say any valid ASCII, so a fixed 26-slot array is too small; 128 or a hash map.
Full Solution — all languages
class Solution:
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
st, ts = {}, {}
for a, b in zip(s, t):
if a in st and st[a] != b:
return False
if b in ts and ts[b] != a:
return False
st[a] = b
ts[b] = a
return Trueimport java.util.*;
class Solution {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character,Character> st = new HashMap<>(), ts = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i), b = t.charAt(i);
if (st.containsKey(a) && st.get(a) != b) return false;
if (ts.containsKey(b) && ts.get(b) != a) return false;
st.put(a, b);
ts.put(b, a);
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isIsomorphic(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char,char> st, ts;
for (int i = 0; i < (int)s.size(); i++) {
char a = s[i], b = t[i];
if (st.count(a) && st[a] != b) return false;
if (ts.count(b) && ts[b] != a) return false;
st[a] = b;
ts[b] = a;
}
return true;
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isIsomorphic = function(s, t) {
if (s.length !== t.length) return false;
const st = {}, ts = {};
for (let i = 0; i < s.length; i++) {
const a = s[i], b = t[i];
if (st[a] !== undefined && st[a] !== b) return false;
if (ts[b] !== undefined && ts[b] !== a) return false;
st[a] = b;
ts[b] = a;
}
return true;
};