I create two maps to check if the order of characters are preserved. t is used as pattern for s and s also a pattern for t. if the two patterns d not match then we return false
-
Time complexity: O(N)
-
Space complexity: O(N)
function isIsomorphic(s: string, t: string): boolean {
let map = new Map()
let reverseMap = new Map()
let sArr = s.split("")
let tArr = t.split("")
if (s.length !== t.length) return false
for (let i = 0; i < sArr.length; i++) {
let a = sArr[i]
let b = tArr[i]
if ((map.has(a) && map.get(a) !== b)
|| (reverseMap.has(b) && reverseMap.get(b) !== a)) {
return false
}
if (!map.has(a) || !reverseMap.has(b)) {
map.set(a, b)
reverseMap.set(b, a)
}
}
return true
};