Bucket Words That Share the Same Letters
Arrays & HashingAuto-graded · 18 test casesLast updated
Partition a list of lowercase words into buckets of mutual rearrangements, using a canonical key and a hash map while keeping a deterministic output order.
Bucket Words That Share the Same Letters
You are given a list of lowercase words. Two words are rearrangements of each other if one can be turned into the other by reordering its letters. Both words must then use exactly the same letters with exactly the same number of occurrences of each. The empty string is a rearrangement only of another empty string.
Split the list into buckets so that every bucket holds words that are rearrangements of one another, and no two buckets contain words that are rearrangements of each other.
Output format
Return a list of buckets, where each bucket is a list of strings. To make the result unique, follow these ordering rules exactly:
- Buckets appear in the order in which their first member appears in the input.
- Inside a bucket, words keep the same relative order they had in the input.
- Every input word appears in the output exactly once. Duplicate words are all kept and land in the same bucket.
- If the input list is empty, return an empty list.
Constraints
0 <= len(words) <= 10^40 <= len(words[i]) <= 100- Each
words[i]contains only lowercase English letters (atoz).
Examples
Example 1
Input: bucket_rearrangements(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Example 2
Input: bucket_rearrangements([''])
Output: [['']]
Hints
Hint 1
Think about a value you can compute from a single word that comes out identical for every rearrangement of it, and different for any word that is not a rearrangement.
Hint 2
Use that value as a dictionary key, and append each original word to the list stored under its key. The key must be hashable, so use a string or tuple rather than a list.
Hint 3
Python dictionaries remember insertion order, so reading the values at the end gives buckets ordered by first appearance, with words inside each bucket in input order. A 26-slot letter-count tuple is an alternative key that avoids sorting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two words are rearrangements of each other exactly when they contain the same multiset of letters. Sorting a word's letters turns that multiset into one fixed string, so it works as a canonical key:
- Every rearrangement of a word sorts to the same string.
- Words that are not rearrangements sort to different strings.
We walk through the input once. For each word we compute its sorted-letter key and append the word to the list stored under that key in a dictionary. At the end, the dictionary's values are the buckets.
Why it is correct
- If two words share a key, their sorted letters are identical, so they have the same letter multiset and are rearrangements of each other.
- If two words are rearrangements, reordering letters does not change the multiset, so they sort to the same key and end up in the same bucket.
- Each word is appended exactly once, so nothing is lost, and duplicates naturally share a bucket.
- Python dictionaries preserve insertion order. A key is inserted when its first word is seen, which gives buckets ordered by first appearance. Words are appended in scan order, so each bucket keeps input order.
- The empty string sorts to the empty key, so empty strings group together. An empty input list gives an empty result.
Complexity
Let N be the number of words and K the maximum word length.
- Time: O(N * K log K), since each word is sorted.
- Space: O(N * K) for the dictionary keys and the stored words.
Replacing the sorted key with a tuple of 26 letter counts brings time down to O(N * K), at the cost of a fixed-size key per word.
Reference solution
from collections import defaultdict
from typing import List
def bucket_rearrangements(words: List[str]) -> List[List[str]]:
buckets = defaultdict(list)
for word in words:
key = "".join(sorted(word))
buckets[key].append(word)
return list(buckets.values())