Skip to content
Preptima
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

Related Topics