Group anagrams#

Levels: level-3
Data structures: string, hash-table

LeetCode

Description#

  • Given an array of strings, group anagrams together.

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Example#

text
1Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
2Output:
3[
4  ["ate","eat","tea"],
5  ["nat","tan"],
6  ["bat"]
7]

Python Solution#

py
1import collections
2
3
4class Solution(object):
5    def groupAnagrams(self, strs):
6        ans = collections.defaultdict(list)
7        for s in strs:
8            ans[tuple(sorted(s))].append(s)
9        return ans.values()