Group Anagrams, visualized step by step

Medium One of the Blind 75 interview problems (LeetCode 49). Technique: hash map. Solution in Python, explained at every step.

The problem

You get a list of words. Group the anagrams together: two words are anagrams when they are made of the same letters, the same number of times each, like listen and silent. Return the groups, in any order.

Example: for ["ear", "arc", "rare", "are", "car"], the answer is [["ear", "are"], ["arc", "car"], ["rare"]]. rare has the letters of ear, but one r more, so it is alone.

The words ear, arc, rare, are, car; under them three groups: ear and are with the key aer, arc and car with acr, and rare alone with aerr.
Each group is named by its key, the letters of its words in sorted order.

Try it yourself first: LeetCode 49 ↗. Then step through the solution below.

Brute force

Take the words one by one and test each against the first word of every group so far, by counting the letters of both; join the first group that matches, or start a new one. With n words of up to k letters and as many groups as words, that is O(n2 · k) time.

The key insight

The clue is in the words "made of the same letters". Sort the letters of a word, and every one of its anagrams sorts to the same string: ear, are and era all give aer. Words that are not anagrams never do.

So the sorted letters are a key, and a hash map from each key to its list of words does the grouping in one pass: each word finds its group with one lookup, however many groups there are, with no comparison against the other groups.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Group Anagrams, step by step

Python

from collections import defaultdict def group_anagrams(words):    groups = defaultdict(list)    for word in words:        key = ''.join(sorted(word))        groups[key].append(word)    return list(groups.values())
All steps as text
  1. Five words. Anagrams have the same letters, the same number of times each. Which of these words go together?
  2. groups starts empty. It will map each key, the letters of a word sorted, to the words that have it.
  3. word takes the first word, ear.
  4. The letters of ear, e, a and r, come down beside key. They are not in order yet.
  5. Sorted, they line up as a, e, r: the key of ear is aer.
  6. A new row in groups: aer is not there yet, so it gets an empty list.
  7. The word ear goes into the list of aer.
  8. Next, arc: its letters a, r, c come down beside key.
  9. Sorted: a, c, r. The key of arc is acr.
  10. A new row in groups: acr is not there yet, so it gets an empty list.
  11. The word arc goes into the list of acr.
  12. Next, rare: its letters r, a, r, e come down beside key.
  13. Sorted: a, e, r, r. The key is aerr: one r more than aer, so not the key of ear.
  14. A new row in groups: aerr is not there yet, so it gets an empty list.
  15. The word rare goes into the list of aerr.
  16. Next, are: its letters a, r, e come down beside key.
  17. Sorted: a, e, r. That is aer, the key of ear.
  18. The key aer lights up in groups: it is there already, with ear.
  19. The word are joins the list of aer, after ear.
  20. Next, car: its letters c, a, r come down beside key.
  21. Sorted: a, c, r. That is acr, the key of arc.
  22. The key acr lights up in groups: it is there already, with arc.
  23. The word car joins the list of acr, after arc.
  24. The words are over. Return the lists in groups: [ear, are], [arc, car] and [rare].
  25. Each word was sorted once: O(n · k log k) time for n words of up to k letters, and O(n · k) space.
Group Anagrams, step by step. Last step: Each word was sorted once: O(n · k log k) time for n words of up to k letters, and O(n · k) space.

Note

In Python, sorted gives a list, and a list cannot be a dictionary key, so the code joins the letters back into a string. In Java, sorting gives a char[], and a map compares arrays by where they are in memory, so every word would get a group of its own: make a String from it.

Complexity

ApproachTimeSpace
Brute force: test each word against every groupO(n2 · k)O(n · k)
Sorted letters as the key of a hash map this pageO(n · k log k)O(n · k)
Letter counts as the keyO(n · k)O(n · k)

n is the number of words, and k the length of the longest one.

  • Time: O(n · k log k). Each of the n words is sorted once, O(k log k) for up to k letters, then looked up in O(k) to hash its key.
  • Space: O(n · k). The map holds every word once, in its group, and one key per group.

Edge cases

  • An empty word, [""]: its key is the empty string, and it is a group of its own: [[""]].
  • One word: one group with it.
  • The same word twice, like ["tea", "tea"]: both get the key aet and share a group: [["tea", "tea"]].
  • No anagrams at all, like ["ab", "cd"]: every key is new, and each word is a group of one.

Try it: put Group Anagrams together step by step

The blocks below are steps of Group Anagrams in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example, ["ear", "arc", "rare", "are", "car"], so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Group Anagrams together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

Can the key cost less than sorting? Yes: count the letters. With only the 26 lowercase letters, a key of 26 counts is built in O(k), so the whole is O(n · k). Keep the counts apart, as a tuple or with a separator such as 1#0#2#…: run together, the counts 1 and 11 read the same as 11 and 1.

The data structure behind it

  • Hash table: a hash map step by step; here each word's sorted letters are the key, and the key finds its list in O(1) on average.