7 lines JavaScript solution O(n) time, O(m) space, m is the length of return array.

  • 0

    Because all anagrams has one unique presentation, for example, "aab" can stand for "aab", "aba", "baa". Using hashMap definitely helps the program here. The unique sorted presentation can be the map's key. For this question, it requires row number as map's value. We can solve it by looping n times and put each element into certain row once row number can be found in the map. By default we add a new row if the map doesn't have its row number.

     * @param {string[]} strs
     * @return {string[][]}
    var groupAnagrams = function(strs) {
          var rtn = new Array(0), r = 0, m = new Map();
          for(var i in strs){
              var k = strs[i].split('').sort().join('');
              if(m.has(k)) (rtn[m.get(k)]).push(strs[i]);
              else {m.set(k, r++); rtn.push([strs[i]]);}
          return rtn;

  • 0

    How can it be O(n) since you're using sort? Be careful.

  • 0

    @cysmith Thanks pointing that. I agree with you regarding this code.

Log in to reply

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