205. Isomorphic Strings
Asked at 15Bloomberg55Amazon48Microsoft47Google45Meta41Accenture54tcs27Remitly100Sprinklr72Yandex71Zomato62LinkedIn62American Express53Zoho52Oracle35
Problem
Two strings s and t of equal length are isomorphic if the characters of s can be replaced to get t, where each character maps to exactly one character, consistently, and no two characters map to the same one. Decide whether s and t are isomorphic.
Example: s = "egg", t = "add" → true; s = "foo", t = "bar" → false
Need a bijection: map s→t and t→s. A conflict in either direction → false.
Complexity: O(n).
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
st, ts = {}, {}
for a, b in zip(s, t):
if st.setdefault(a, b) != b or ts.setdefault(b, a) != a:
return False
return True
assert Solution().isIsomorphic("egg", "add") is True
assert Solution().isIsomorphic("foo", "bar") is False
assert Solution().isIsomorphic("badc", "baba") is False
class Solution {
public boolean isIsomorphic(String s, String t) {
int[] st = new int[256], ts = new int[256]; // store last index+1 seen
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i), b = t.charAt(i);
if (st[a] != ts[b]) return false; // must have been paired together before (or never)
st[a] = ts[b] = i + 1;
}
return true;
}
}
func isIsomorphic(s string, t string) bool {
var st, ts [256]byte // 0 = not mapped yet
for i := 0; i < len(s); i++ {
a, b := s[i], t[i]
if st[a] == 0 && ts[b] == 0 {
st[a], ts[b] = b, a
} else if st[a] != b || ts[b] != a {
return false
}
}
return true
}