Cluster Words by Letter Inventory
StringsAuto-graded · 18 test casesLast updated
Tests whether you can use a canonical character-frequency key and a hash map to partition a list of strings into anagram groups in linear time.
Problem
You are given a list of lowercase words. Two words belong to the same cluster if one can be formed by rearranging the letters of the other — that is, they share exactly the same letters with exactly the same counts.
Write a function that partitions the input list into clusters and returns them. Every word must appear in exactly one cluster. Clusters may be returned in any order, and words within a cluster may also appear in any order.
Constraints
0 <= len(words) <= 10^40 <= len(words[i]) <= 100- Each
words[i]contains only lowercase English letters (a–z).
Examples
Example 1
Input: cluster_by_letter_inventory(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Example 2
Input: cluster_by_letter_inventory([''])
Output: [['']]
Hints
Hint 1
Two words are in the same cluster when and only when their per-letter counts are identical — think about what makes a good dictionary key for that property.
Hint 2
A tuple of 26 integers, one count per letter a–z, is hashable and uniquely identifies a letter inventory. Build it in O(k) time per word by iterating once over the word's characters.
Hint 3
Use a dict that maps each inventory tuple to the list of words that share it. One pass over the input fills the dict; returning its values gives you the clusters.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
Two words are anagrams of each other if and only if they have the same letter-frequency profile — each letter of the alphabet appears the same number of times in both words. So we need a canonical key that is identical for all anagrams of a word and distinct for everything else.
A tuple of 26 integers works perfectly: index 0 holds the count of 'a', index 1 the count of 'b', and so on up to index 25 for 'z'. Because tuples are hashable, this key can live directly in a dictionary.
Algorithm
- Create an empty dict
clusters. - For each word, allocate a 26-element list of zeros and increment
counts[ord(ch) - ord('a')]for every characterchin the word. - Convert
countsto atuple(lists are mutable and cannot be dict keys). - Append the word to
clusters[key], creating a new list if the key has not been seen before (dict.setdefaulthandles this in one step). - Return
list(clusters.values()).
Why it is correct
- Same key → anagrams: two words with identical 26-count vectors contain the same letters with the same multiplicities, so one is a rearrangement of the other.
- Anagrams → same key: rearranging letters leaves every count unchanged, so anagrams always produce the same tuple.
- Every input word is appended to exactly one list, so the result is a true partition — nothing is missed or duplicated.
Edge cases
| Input | Output | Reason |
|---|---|---|
[] | [] | The loop never runs. |
[""] | [[""]] | The empty string maps to the all-zero tuple. |
["a", "a"] | [["a", "a"]] | Both land on the same key. |
["aab", "abb"] | [["aab"], ["abb"]] | Different counts → different keys. A set-based key would wrongly merge these. |
Complexity
Let n be the number of words and k the length of the longest word.
- Time: O(n · k). Building the count array and hashing the 26-tuple is O(k + 26) = O(k) per word.
- Space: O(n · k) for the output (unavoidable — every character of every word is returned). The dictionary keys add O(g · 26) where g is the number of distinct clusters.
This beats the sorting approach, which costs O(n · k log k) because sorting each word takes O(k log k).
Reference solution
from typing import List
def cluster_by_letter_inventory(words: List[str]) -> List[List[str]]:
clusters = {}
for word in words:
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord('a')] += 1
key = tuple(counts)
clusters.setdefault(key, []).append(word)
return list(clusters.values())