Medium · Frequency Key
Understand → Visualise → Practice.
Anagrams differ only in character order. A canonical key lets a hash map collect all words with the same letters.
Use the sorted letters, or a 26-count tuple, as the map key for each word.
Sort the characters or count them.
map[key].append(word).
Each bucket is one anagram group.
With sorting, O(n·k log k) time for n words of maximum length k; O(n·k) space.
A set of letters is not enough: `abb` and `ab` have different counts.
Read the full guide first: Hash Maps and Hash Sets.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.