TRT
Sign in
mediumFoundationsLeetCode#hash map#canonical key

Group anagrams

Group the words in a list that are anagrams of each other, using a key that every anagram of a word shares.

The Runtime Theory Team1 min read
Taught inHash maps in your languagePython, Java, JavaScript, Go, C++ and Rust all ship a hash map. They differ in how they resolve collisions and what they promise about order, and they share the same traps.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

in["eat", "tea", "tan", "ate", "nat", "bat"]

out[["bat"], ["nat", "tan"], ["ate", "eat", "tea"]] in any order

in[""]

out[[""]]

in["a"]

out[["a"]]

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

  1. Sorting a word's letters gives a key: "eat", "tea" and "ate" all become "aet".
  2. Counting letters gives a key without sorting: 26 counts, one per letter. Which is faster for long words?
  3. 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 String built 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.

Not started

Sign in to save your learning progress.

Sign in to save