mediumCodingEntryMidSenior
Group a list of words so that words which are anagrams of each other end up together. What is your key, and what does it cost?
5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup
Answer
Short answer
Every anagram class needs one canonical key: either the word's letters sorted, or a vector of letter counts. The counting key is cheaper but only if the counts are separated when they are turned into a string, because concatenating them lets a count of eleven and a count of one swap places unnoticed.
Was this answer helpful?
Likely follow-ups
- Return only the groups with more than one member, and stream the input rather than holding it. What can you drop?
- The words are hundreds of thousands of characters long. Which key do you want now?
- Group by anagram class where the comparison ignores case and accents. What has to happen first?
- How would you shard this across machines so that a group never splits across two of them?
Related questions
- Count the subarrays whose elements sum to k, where the values may be negative.mediumAlso on hashing and hash-map4 min
- Find the length of the longest substring without repeating characters.mediumAlso on hashing2 min
- Insert, delete and get-a-uniformly-random-member all have to be O(1). What breaks when you delete from the middle?mediumAlso on hash-map6 min
- A cache must evict the least recently used entry and every operation has to be O(1). Which two structures do you need, and why is one of them not enough?mediumAlso on hash-map5 min