Group words by character frequency using a hashmap
The sorting-based approach sorts each word's characters in O(k log k), yielding O(n · k log k) total. By counting character frequencies instead of sorting, we reduce per-word cost from O(k log k) to O(k), exploiting the fixed 26-letter alphabet as a constant-size domain.
The 26-element frequency array acts as a perfect hash for anagram equivalence — two words are anagrams if and only if they have identical character frequency distributions.
Every input word must appear in exactly one output group. Since we store all n words in the hashmap, and the total character count across all words is n · k, the space is necessarily O(n · k). The 26-element frequency array adds only O(1) overhead per iteration.
The space is dominated by the output itself — any algorithm that groups n words of average length k must use at least O(n · k) space to store the result.