Skip to the solution
MediumDSA13 min read

How do you group anagrams together?

568 views

The problem

Question presented to candidate: "Given a list of strings, group the anagrams together and return the groups in any order — for example ["eat", "tea", "tan", "ate", "nat", "bat"] becomes [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]. Please solve it in Python and give me the complexity."

What a strong answer should cover:

  • The idea of a canonical key shared by all anagrams, and a hash map from key to list of words, built in one pass.
  • Two keys: the sorted letters, O(k log k) per word, and a 26-letter count, O(k) per word; total O(n · k log k) or O(n · k).
  • O(n · k) space for keys and output, and why the pairwise brute force is O(n² · k).
  • Python specifics: collections.defaultdict(list); keys must be hashable, so "".join(sorted(w)) or tuple(...), never a list; dict preserves insertion order, so groups come out in first-seen order.
  • Edge cases: empty list, empty string, same letters with different counts.

Clarifying questions expected:

  • Only lowercase a–z? Does the output order matter?

Code / implementation expected: Yes — a group_anagrams(words) function in Python using a dict/defaultdict, run on the sample and on edge cases.

  • strings
  • hashing

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read · 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonGroup anagrams with a sorted-string key on six inputs
PythonSorted key vs letter-count key: same groups, different cost

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 83 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the longest substring without repeating characters?

Continue