KatInterview

Bucket Words by Letter Multiset Without Per-Word Sorting

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashinghash-mapstringsanagrams

Last 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 a to z (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.