Skip to content
Home » Leetcode 205 Isomorphic Strings

Leetcode 205 Isomorphic Strings

Leetcode 205 Isomorphic Strings

The intuition is pretty straight forward which is to use map. But we have to keep two separate maps to record the mapping from s to t and the other from t to s. Then we loop through s and generate a temporary string, at the end we just check if the new string equals to t.

One short circuit in the for loop is that, if a letter from s does not have a mapped letter yet but the for the letter of the same index in t is already mapped to another letter in s, we return false directly. This is because one letter cannot be mapped to two different letters.

Solution

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isIsomorphic = function(s, t) {
    let mappedString = '';
    let map = {};
    let reversedMap = {}

    for(let i = 0; i < s.length; i++) {
        if(map[s[i]]) {
            mappedString += map[s[i]]
        } else if(reversedMap[t[i]]) {
            return false
        } else {
            map[s[i]] = t[i]
            reversedMap[t[i]] = s[i]
            mappedString += map[s[i]]
        }
    }

    return mappedString === t
};

Time Complexity:
O(n)

Space Complexity:
O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *