Skip to content

49. Group Anagrams

https://leetcode.com/problems/group-anagrams/

js
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
  var map = {}
  strs.forEach(str => {
    let key = str.split('').sort().join('')
    map[key] = map[key] || []
    map[key].push(str)
  })
  return Object.keys(map).map(k => map[k])
}
py
class Solution(object):

    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        lookup = {}
        for word in strs:
            key = ''.join(sorted(word))
            if key in lookup:
                lookup[key].append(word)
            else:
                lookup[key] = [word]
        return list(lookup.values())