Ctrl K

Anagram Buckets

Medium
You are given an array of strings words. Two strings are anagrams when one can be turned into the other by rearranging its letters, that is, both contain the same letters the same number of times. Split the strings into groups so that every group holds strings that are anagrams of one another, and strings from different groups are not. Every element of the array, duplicates included, must land in exactly one group. Return the list of groups. The groups, and the strings inside each group, may come in any order.
Example 1
words=['listen', 'google', 'silent', 'cat', 'enlist', 'act'] → [['listen', 'silent', 'enlist'], ['google'], ['cat', 'act']]

"listen", "silent" and "enlist" are made of the same letters, so are "cat" and "act", while "google" has no match and forms a group of its own.

Example 2
words=['', 'b', ''] → [['', ''], ['b']]

The two empty strings are anagrams of each other and share a group; "b" stands alone.

Example 3
words=['ab', 'ba', 'aab'] → [['ab', 'ba'], ['aab']]

"aab" has two a's, so it cannot join "ab" and "ba".

Constraints
  • 1 ≤ words.length ≤ 10⁴
  • 0 ≤ words[i].length ≤ 100
  • words[i] consists of lowercase English letters only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Subsequence of One Word Only MediumMost Searched Words MediumWord Grown Letter by Letter MediumMerge Contact Cards MediumWords Hidden in a Text Medium
loading Python…
Input
words=['listen', 'google', 'silent', 'cat', 'enlist', 'act']
Expected
[['listen', 'silent', 'enlist'], ['google'], ['cat', 'act']]

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.