Group Anagrams
Every anagram shares the same sorted-letter key (e.g. "eat" and "tea" both sort to "aet"). Bucket each word by that key in a map, then return the buckets. Reach for it whenever grouping strings by a shared signature.
Details
Animated on: ["eat","tea","tan","ate","nat","bat"] — group words that are anagrams of each other
Problem:Group AnagramsMedium
Pattern:Hashing and Frequency Maps
Strings
step 1 / 8
For each word, sort its letters into a key and drop it into that key's bucket.
1FUNCTION groupAnagrams(words):2 make an empty lookup table (sorted-letters key -> list of words)3 FOR each word in words:4 key = the word's letters sorted and joined into a string5 IF key is not in the table: store key -> an empty list6 add word to the list stored for key7 END FOR8 RETURN all the lists in the table9END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- For each word, sort its letters into a key and drop it into that key's bucket.
- "eat" sorts to "aet" — new bucket. groups = { aet: [eat] }.
- "tea" sorts to "aet" too — same bucket as "eat". groups = { aet: [eat, tea] }.
- "tan" sorts to "ant" — new bucket. groups = { aet: [eat, tea], ant: [tan] }.
- "ate" sorts to "aet" — joins the first bucket. groups = { aet: [eat, tea, ate], ant: [tan] }.
- "nat" sorts to "ant" — joins the second bucket. groups = { aet: [...3], ant: [tan, nat] }.
- "bat" sorts to "abt" — new bucket, no other word shares it. groups = { aet: [...3], ant: [...2], abt: [bat] }.
- Return the buckets: [["eat","tea","ate"], ["tan","nat"], ["bat"]] — 3 anagram groups from 6 words.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.