A few JavaScript solutions


  • 0

    The standard solution using a map:

    var isAnagram = function(s, t) {
        if (t.length !== s.length) return false;
        const counts = {};
        for (let c of s) {
            counts[c] = (counts[c] || 0) + 1;
        }
        for (let c of t) {
            if (!counts[c]) return false;
            counts[c]--;
        }
        return true;
    };
    

    ...which can be "minified" to:

    var isAnagram = function(s, t, m = {}) {
        for (let c of s) m[c] = (m[c] || 0) + 1;
        for (let c of t) if (!m[c]--) return false;
        return Object.values(m).every(v => !v);
    };
    

    Using an array as buckets:

    var isAnagram = function(s, t) {
        if (t.length !== s.length) return false;
        const counts = [];
        for (let c of s) {
            let i = c.charCodeAt(0) - 'a'.charCodeAt(0);
            counts[i] = (counts[i] || 0) + 1;
        }
        for (let c of t) {
            let i = c.charCodeAt(0) - 'a'.charCodeAt(0);
            if (!counts[i]) return false;
            counts[i]--;
        }
        return true;
    };
    

    One-liner (log n times slower) using sort:

    var isAnagram = function(s, t) {
        return s.split('').sort().join('') === t.split('').sort().join('');
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.