PracticeNeetCode ↗LeetCode ↗
Given an array of strings strs, group the anagrams together. The order of the groups and the order within a group don't matter.
groups: signature → list of strings.s, build a 26-length count array of its letters.groups, appending s to that key's list.groups.values()) once every string has been processed.Time: O(n · k) where k is the max string length — Space: O(n · k)
from collections import defaultdict
def groupAnagrams(strs: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for s in strs:
count = [0] * 26
for ch in s:
count[ord(ch) - ord('a')] += 1
groups[tuple(count)].append(s)
return list(groups.values())How the solution above works, piece by piece.
groups = defaultdict(list): key → list of words. defaultdict creates an empty list the first time a key is used.count = [0] * 26, one slot per letter, and add 1 for every character (ord(ch) - ord('a') gives the slot).tuple(count): lists can't be dictionary keys, tuples can. Two words are anagrams exactly when their tuples are equal.groups[key].append(s) puts the word into its group.list(groups.values()) returns the groups. O(n · k) for n words of length k, faster than sorting each word (O(n · k log k)).Running it on strs = ["eat", "tea", "tan", "ate", "nat", "bat"]: