Given a list of words, group together the ones that are anagrams of each other. The groups and the words inside them can come back in any order.
Before you code
The trick is choosing the key. Every anagram of a word has the same letters, so a key built from the letters alone, ignoring their order, puts all of them in the same group. The map goes from that key to the list of words that share it.
Hints
- Sorting a word's letters gives a key: "eat", "tea" and "ate" all become "aet".
- Counting letters gives a key without sorting: 26 counts, one per letter. Which is faster for long words?
- The key must be immutable. In Python a list of counts can't be a dictionary key, but a tuple can; in Java, use a
Stringbuilt from the counts.
Production & complexity notes
When solving Group anagrams on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Hash maps in your language to reinforce the underlying pattern.
What it practices
Designing a key whose hash and equality agree, and keeping it immutable, from Hash maps in your language.