You are given an array of strings — ["eat", "tea", "tan", "ate", "nat", "bat"] — and asked to group the anagrams together. The first approach that springs to mind is the obvious one: compare every pair of strings, check whether they use the same letters, and merge groups as matches are found. It feels reasonable. It is also a trap.
Consider what “compare every pair” actually means. With 6 strings, you have 15 possible pairs. With 100 strings, that number balloons to 4,950. With 1,000 strings, you are staring down nearly 500,000 pair comparisons — and each comparison itself costs O(k) time to check character-by-character. The total work is O(n^2 * k), which is devastating for large inputs.
Imagine a filing cabinet where every document must be compared against every other document to decide which folder it belongs in. No labels, no categories — just raw comparison. What if every document carried a standardized label on its cover, and identical labels meant “same folder”? That is the insight we are building toward. But first, feel the pain.
Start by checking pairs, one at a time.
Pair 1: Are "eat" and "tea" anagrams?
Will “eat” and “tea” be anagrams of each other?