Determine if two strings are isomorphic using character mapping.
Problem Statement
Examples
Input: s = "egg", t = "add"
Output: true
Explanation: Each character maps uniquely to a target character preserving order.
Input: s = "foo", t = "bar"
Output: false
Explanation: Characters cannot be mapped consistently between both strings.
Input: s = "paper", t = "title"
Output: true
Explanation: Each character maps uniquely to a target character preserving order.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Two strings are isomorphic if there is a 1-to-1 bijection between characters. We can track character mappings in both directions (s -> t and t -> s) to verify that neither character maps to multiple values.
Step-by-Step Approach
- If
s.length !== t.length, returnfalse. - Maintain two maps:
m1(s -> t) andm2(t -> s). - Iterate through index
i: - If
m1.has(s[i]) && m1.get(s[i]) !== t[i], returnfalse. - If
m2.has(t[i]) && m2.get(t[i]) !== s[i], returnfalse. - Record mappings
m1.set(s[i], t[i])andm2.set(t[i], s[i]). - Return
true.
Optimal Implementation (JavaScript)
function isIsomorphic(s, t) {
if (s.length !== t.length) return false;
const m1 = new Map(), m2 = new Map();
for (let i = 0; i < s.length; i++) {
const c1 = s[i], c2 = t[i];
if (m1.has(c1) && m1.get(c1) !== c2) return false;
if (m2.has(c2) && m2.get(c2) !== c1) return false;
m1.set(c1, c2);
m2.set(c2, c1);
}
return true;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Duplicate character mapping: "badc" and "baba" -> false.
- Different length strings -> false.
- Single character strings -> true.