JavaScript Solution that Beats 81% with Explanation


  • 2
    I
    /**
     * @param {string[]} strs
     * @return {string[][]}
     */
    var groupAnagrams = function(strs) {
        var resultObj = {} ,resultArr = [];
        function addIndexToObj (element) {
            var key = element.split("").sort().join("");
            if (resultObj.hasOwnProperty(key)) {
                resultObj[key].push(element);
            } else {
                resultObj[key] = [element];
            }
        }
        strs.forEach(addIndexToObj);
        
        for (var key in resultObj) {
            resultArr.push(resultObj[key].sort());
        }
        
        return resultArr;
    };
    

    What I was thinking was:

    1: Created an object to store input strings that have the same value after sorted each string. (Group input strings).

    2: Since I stored grouped numbers in arrays, I can just get each array, sort, then put into a result array.

    Note

    array.prototype.sort()
    

    is already in lexicographic order. In order to sort an array with numbers , we pass below function as sort's parameter

    function(a, b) {
        return a - b;
    }

  • 0
    R

    No need for the second sort in the last for loop. This solution gets AC as well:

    var groupAnagrams = function(strs) {
      var resultObj = {}, resultArr = [];
      function addIndexToObj (element) {
          var key = element.split("").sort().join("");
          if(resultObj.hasOwnProperty(key)) {
              resultObj[key].push(element);
          } else {
              resultObj[key] = [element];
          }
      }
      strs.forEach(addIndexToObj);
      
      for(var key in resultObj) {
          resultArr.push(resultObj[key]);
      }
      return resultArr;
    };
    

  • 0
    U

    Same idea, using javascript array reduce to construct the map.

    const groupAnagrams = (words) => {
      if (words.length === 0) return [''];
      return Array
      .from(
          words.reduce((wordMap, word) => {
              let curKey = word.split('').sort().join('');
              wordMap.has(curKey) ? wordMap.get(curKey).push(word) : wordMap.set(curKey, [word]);
              return wordMap;
          }, new Map())
            .values()
          );
    };
    

Log in to reply
 

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