Isomorphic Strings
Problem Statement
You’re a pattern matcher with two strings. Are they isomorphic—can one map to the other with a consistent character substitution? This easy-level hashing puzzle is a code-cracking caper—use maps to ensure the transformation holds!
Example
Input: s = "egg", t = "add"
Output: true (e→a, g→d)
Input: s = "foo", t = "bar"
Output: false (f→b, o→a vs o→r fails)
Input: s = "paper", t = "title"
Output: true (p→t, a→i, etc.)
Code
Java
Python
JavaScript
public class Solution { public boolean isIsomorphic(String s, String t) { if (s.length() != t.length()) return false; MapsToT = new HashMap<>(); Map tToS = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char sc = s.charAt(i), tc = t.charAt(i); if (sToT.containsKey(sc) && sToT.get(sc) != tc) return false; if (tToS.containsKey(tc) && tToS.get(tc) != sc) return false; sToT.put(sc, tc); tToS.put(tc, sc); } return true; } }
def is_isomorphic(s, t): if len(s) != len(t): return False s_to_t, t_to_s = {}, {} for sc, tc in zip(s, t): if (sc in s_to_t and s_to_t[sc] != tc) or (tc in t_to_s and t_to_s[tc] != sc): return False s_to_t[sc] = tc t_to_s[tc] = sc return True
function isIsomorphic(s, t) { if (s.length !== t.length) return false; let sToT = new Map(), tToS = new Map(); for (let i = 0; i < s.length; i++) { let sc = s[i], tc = t[i]; if ((sToT.has(sc) && sToT.get(sc) !== tc) || (tToS.has(tc) && tToS.get(tc) !== sc)) { return false; } sToT.set(sc, tc); tToS.set(tc, sc); } return true; }
Explanation
- Hashing Insight: Two maps ensure a one-to-one mapping in both directions.
- Flow: Map s chars to t chars and vice versa; any mismatch breaks isomorphism.
- Example Walkthrough: "egg","add" → sToT={e:a,g:d}, tToS={a:e,d:g} → true.
- Edge Case: "badc","baba" fails (c and d can’t both map to a).
- Why Two Maps? Ensures bijection—no two chars map to the same target.
Note
Time complexity: O(n), Space complexity: O(k) where k is charset size. A mapping marvel for pattern sleuths!