Intuitive Javascript Solution


  • 0
    D
    var isAnagram = function(s, t) {
        // anagram contains the same set of characters
        return s.split('').sort().join('') === t.split('').sort().join('');
    };
    

  • 0

    Your solution is definately simple and easy to read. However, technically, it's a lot slower because sorts are slow. Let's say your anagrams were 5000 letters long. This algorithm below will do it in O(2*n) time.

    var isAnagram = function(s, t) {
        
        const hash = {};
        
        if( s.length != t.length ) return false;
        
        // convert first anagram into hashmap with letter counts
        s.split('').reduce( (acc, val) => {
            if( val in acc ) acc[val]++;
            else acc[val] = 1;
            return acc;
        }, hash);
        
        // iterate over second anagram, subtracting letter counts
        for( let i = 0; i < t.length; i++ ) {
            if( t[i] in hash ) {
                if( --hash[t[i]] < 0 ) return false;
            } else {
                // letter doesn't exist, not an anagram
                return false;
            }
        }
        
        return true;
    };
    

Log in to reply
 

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