Group Anagrams
LC 49Given an array of strings, group the anagrams together.
["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]]
Show solution
Insight: All anagrams share the same character-count signature — use it as a dict key.
from collections import defaultdict
def groupAnagrams(strs):
groups = defaultdict(list)
for s in strs:
key = [0] * 26
for c in s:
key[ord(c) - ord('a')] += 1
groups[tuple(key)].append(s)
return list(groups.values())
Complexity: O(n·k) time, O(n·k) space. (Sorting each word as the key is O(n·k log k) and also fine.)