Check if two strings are isomorphic
Problem
Two strings are isomorphic if the characters of s can be replaced to get t, using a consistent one-to-one mapping (no two characters map to the same character). Return true if they are.
Example 1
Input: s = "egg", t = "add" Output: true
Example 2
Input: s = "foo", t = "bar" Output: false
Example 3
Input: s = "badc", t = "baba" Output: false
Also asked as: Check if two given strings are isomorphic to each other
Test cases
Case 1
Input: "egg", "add" Expected: true
Case 2
Input: "foo", "bar" Expected: false
Case 3
Input: "badc", "baba" Expected: false
Case 4
Input: "paper", "title" Expected: true
View solutionHide solution1 approach
1. Two consistency maps
Time O(n)Space O(1)
Each char of a must map to exactly one char of b and vice-versa.
function isIsomorphic(a, b) { if (a.length !== b.length) return false; const ab = new Map(), ba = new Map(); for (let i = 0; i < a.length; i++) { if (ab.has(a[i]) && ab.get(a[i]) !== b[i]) return false; if (ba.has(b[i]) && ba.get(b[i]) !== a[i]) return false; ab.set(a[i], b[i]); ba.set(b[i], a[i]); } return true;}