Skip to content

Group Anagrams

MediumLeetCode #49Time O(n·k)Space O(n·k)

You get a list of lowercase words. Group together the words that are anagrams of each other (same letters, any order). Return the groups in any order.

["eat", "tea", "tan", "ate", "nat", "bat"]
-> [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Brute force compares every pair of words and checks if they are anagrams, which is O(n²) comparisons. The waste is that you compare words that were never going to match.

Give every word a canonical key that is identical for all anagrams and different otherwise. Then one hash map from key to list of words does all the grouping in a single pass. Two good keys: the word’s sorted letters ("eat" becomes "aet"), or a count of each letter. The count key avoids sorting each word, so it is O(k) per word instead of O(k log k). Mention both; code the count version.

Show solutionHide solution
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for word in strs:
counts = [0] * 26 # letter frequencies are the same for all anagrams
for ch in word:
counts[ord(ch) - ord("a")] += 1
groups[tuple(counts)].append(word)
return list(groups.values())

Let n be the number of words and k the length of the longest word.

  • Time: O(n·k) — each word is scanned once to build its 26-slot count, and the key is a fixed size of 26.
  • Space: O(n·k) — the map stores every word once, plus a fixed-size key per group.
  • Lists can’t be dictionary keys in Python. Convert the count list to a tuple. In TypeScript and Java, join or stringify the counts instead.
  • Delimit the counts in a string key. Joining [1, 11] as "111" collides with [11, 1]. Use a separator, as Arrays.toString and join(',') do.
  • The empty string is valid input and forms its own group.

Are two strings anagrams of each other? The trick: compare letter counts. One 26-slot array, add for the first string, subtract for the second, check all zeros. If characters can be Unicode, use a hash map instead of a fixed array.

Find All Anagrams in a String (LeetCode 438)

Section titled “Find All Anagrams in a String (LeetCode 438)”

Find every start index in s where a substring is an anagram of p. The trick: slide a window of length len(p) over s, updating the letter counts by adding the new character and removing the old one. Compare counts to p’s counts at each step.

Return the k most frequent words, ties broken alphabetically. The trick: count with a hash map, then sort or use a heap with the key (-count, word).