JavaScript solution, fast and simple


  • 0
    V

    We can use hash function based on prime numbers to compare anagrams and then create "vocabulary" from it.

    /**
     * @param {string[]} strs
     * @return {string[][]}
     */
    var groupAnagrams = function(strs) {
        //first 26 prime numbers to be used in hashing (latin alphabet has 26 letters)
       var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];
        //vocabulary of hash values
       var map = {};
       
       for(var i = 0, len = strs.length; i < len; i++) {
           var s = strs[i];
           var key = hash(s);
           var mapItem = map[key] = map[key] || [];
           mapItem.push(s);
       }
       
       return Object.values(map);
       
       function hash(str){
           var r = 1;
           for(var i = 0, len = str.length; i < len; i++) {
               r *= primes[str.charCodeAt(i) - 97]; //97 is the code for letter "a"
           }
           return r;
       }
    };
    

Log in to reply
 

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