Group anagrams together
Do not compare words with each other. Give each word a canonical key — its letters sorted, or a tuple of letter counts — and use a dictionary to collect words sharing a key. One pass, no pairwise comparison, and the whole O(n²) instinct disappears.
Overview
The instinct, and why it is wrong
The obvious approach compares every word with every other word to see whether they are anagrams. That is n(n−1)/2 comparisons, each costing O(m log m) or O(m), so the whole thing is O(n²·m).
The realisation that fixes it: being anagrams is an equivalence relation, so instead of testing pairs you can give every word a label that all its anagrams share, and group by label. Dictionaries group by label in O(1) each.
Step through it
What to watch
- Each word is looked at once and never compared with another word.
- The key is the group's identity — that is the whole idea.
- Six words: six lookups here, fifteen comparisons the naive way.
Say this out loud
"Map each word to a canonical form - sorted letters - and group by that in a dict. O(n·m log m) for n words of length m, instead of n² pairwise comparisons."