mediumStringHash TableSortingArrays & Hashing

Group Anagrams

mediumTime: O(n * k log k)Space: O(n * k)

Signals to notice

group strings with same charactersanagram groupingcanonical form

Brute force first

Compare every pair of strings for anagram. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Sort each string to get a canonical key, group by key in a hash map. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

Two strings are anagrams if and only if their sorted characters are identical. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Using frequency counting instead of sorting — both work, but sorting is simpler to implement. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern