mediumStringHash TableSortingArrays & Hashing

Group Anagrams

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

Recognize the pattern

group strings with same charactersanagram groupingcanonical form

Brute force idea

The naive version of Group Anagrams sounds like this: 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.

Better approach

The real unlock in Group Anagrams comes when you notice this: 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.

Key invariant

The compass for Group Anagrams is this: 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.

Watch out for

One easy way to drift off course in Group Anagrams is this: 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