Group Anagrams
2 approaches, code in every language
Problem description
You are given a list of lowercase words. Two words belong together when one can be produced by shuffling the letters of the other, using every letter exactly as many times. Your job is to partition the list into buckets so that each bucket holds precisely the words that are rearrangements of one another.
Return the collection of buckets. The buckets may appear in any order, and the words inside a single bucket may also be listed in any order.
Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
"eat", "tea", and "ate" share the same letters, so they land in one bucket. "tan" and "nat" form another, and "bat" stands alone.
Example 2
Input: strs = ["abc","bca","xyz"]
Output: [["abc","bca"],["xyz"]]
"abc" and "bca" are rearrangements of each other; "xyz" matches nothing else.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i] contains only lowercase English letters
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Bin Label Families is our own problem on the technique behind Group Anagrams: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free