242. Valid Anagram

time: O(n)

space: O(1) why? cuz only 26 lowercase alphabets

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    if (s.length !== t.length) return false;

    const memo = {};

    for (const x of s) {
        if (memo[x] === undefined) {
            memo[x] = 0;
        }

        memo[x]++;
    }

    for (const x of t) {
        if (memo[x] === undefined || memo[x] < 0) {
            return false;
        }
        memo[x]--;
    }

    for (const key in memo) {
        if (memo[key] !== 0) return false;
    }

    return true;

};

Last updated