KatInterview

Bucket Words That Share the Same Letters

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashinghash-mapstringssorting

Last 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^4
  • 0 <= len(words[i]) <= 100
  • Each words[i] contains only lowercase English letters (a to z).

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.