Bucket Words by Letter Multiset Without Per-Word Sorting
Arrays & HashingAuto-graded · 19 test casesLast updated
Cluster words that share identical letter counts into ordered buckets, using a hashable frequency key rather than sorting each word's letters, while preserving duplicates and order.
You are given a list of words made only of lowercase letters a to z. Partition the list into buckets so that two words share a bucket exactly when they are anagrams, meaning each letter appears the same number of times in both.
Every entry of the input must appear in the output exactly once. If the same word appears several times, each occurrence is kept and placed in the same bucket.
Output ordering
- Order the buckets by the position of the earliest input entry that belongs to each one. The bucket containing the first input word comes first, and so on.
- Inside a bucket, keep the words in the order they appeared in the input.
This ordering only affects how the result is presented. It does not influence which words are grouped together.
Special cases
- An empty word
""is allowed. All empty words form a single bucket. - An empty input list produces an empty list of buckets.
Restriction
Do not build a key by sorting the characters of each word. Solve it with a different kind of signature, such as letter counts.
Constraints
- Every word consists only of lowercase English letters
atoz(possibly empty). - The input list may be empty.
- Duplicate words may occur and must be preserved.
- The returned buckets must follow the ordering rules above exactly.
Examples
Example 1
Input: bucket_anagrams(['eat', 'tea', 'bat', 'ate', 'bat'])
Output: [['eat', 'tea', 'ate'], ['bat', 'bat']]
Example 2
Input: bucket_anagrams([''])
Output: [['']]
Example 3
Input: bucket_anagrams(['', 'a', '', 'a', 'b'])
Output: [['', ''], ['a', 'a'], ['b']]
Hints
Hint 1
Two words are anagrams exactly when their per-letter counts match. Think about what a fixed-size summary of a word's counts could look like.
Hint 2
Lists cannot be dictionary keys, but a tuple of 26 counts can. Map each count tuple to the list of words that produced it.
Hint 3
A dictionary that remembers insertion order already yields buckets ordered by first appearance, and appending words as you read them keeps the within-bucket order, so no extra sorting is needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two words are anagrams exactly when they have the same count for every letter. So each word gets a signature: a vector of 26 counts, one per letter. Converting it to a tuple makes it hashable, so it can be a dictionary key. Each word is appended to the list stored under its key.
Why it is correct
- Grouping: Two words produce the same tuple if and only if every letter count matches, which is the definition of being anagrams. Different lengths always give different tuples.
- Completeness: Each input word is appended to exactly one list, so every occurrence appears once, and duplicates land together in the same bucket.
- Ordering: Python dictionaries preserve insertion order. A key is inserted when its first member is read, so iterating the values lists buckets by earliest member. Words are appended as they are read, so each bucket keeps input order. No sorting is required.
- Edge cases: An empty list never enters the loop and returns
[]. The empty word gives the all-zero tuple, so all empty words share one bucket.
Complexity
Let n be the number of words and S the total number of characters.
- Time:
O(S + 26n), since counting is linear in the characters and each word does constant extra work for the 26-slot tuple and its hash. - Space:
O(26n + S)for the keys and the output.
Reference solution
from typing import List
def bucket_anagrams(words: List[str]) -> List[List[str]]:
buckets = {}
for word in words:
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord('a')] += 1
key = tuple(counts)
buckets.setdefault(key, []).append(word)
return list(buckets.values())