Group Scrambled Words by Shared Anagram Fingerprint
StringsAuto-graded · 17 test casesLast updated
Tests the ability to canonicalize strings into sorted-character keys and cluster words that are anagrams of each other, with a precise tie-breaking rule for deterministic output.
Group Scrambled Words by Shared Anagram Fingerprint
A word cluster is a maximal collection of strings that are all anagrams of one another — that is, each string in the cluster contains exactly the same characters with the same frequencies, just potentially in a different order.
Given a list of lowercase strings words, return all word clusters as a list of lists. The output must be ordered and formatted according to the following tie-breaking rules, so that exactly one correct answer exists:
- Within each cluster, sort the strings lexicographically (ascending).
- Sort the clusters themselves by their lexicographically smallest element (ascending). If two clusters share the same smallest element (impossible by definition, since each string belongs to exactly one cluster), break ties by the second element, and so on — but this case will not arise.
What counts as an anagram?
Two strings are anagrams if and only if they consist of the same multiset of characters. For example, "listen" and "silent" are anagrams; "hello" and "world" are not.
Constraints
0 <= len(words) <= 20000 <= len(words[i]) <= 50- Every character in
words[i]is a lowercase English letter (a–z). wordsmay contain duplicate strings; duplicates are kept (they are trivially anagrams of each other and belong to the same cluster).- The empty string
""is a valid word; all empty strings belong to the same cluster.
Examples
Example 1
Input: group_anagram_clusters(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
Output: [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]
Example 2
Input: group_anagram_clusters([''])
Output: [['']]
Example 3
Input: group_anagram_clusters(['ab', 'ba', 'cd', 'dc', 'abc', 'bca', 'cab'])
Output: [['ab', 'ba'], ['abc', 'bca', 'cab'], ['cd', 'dc']]
Hints
Hint 1
Think about what property two anagram strings always share — what single transformation makes them identical?
Hint 2
Use that shared property as a dictionary key to collect strings into buckets, then apply the required sorting to each bucket and to the list of buckets at the end.
Hint 3
Handle the empty string carefully: it is its own valid key and will form a cluster with any other empty strings in the input.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Insight: Canonical Form as Hash Key
Two strings are anagrams if and only if sorting their characters produces the same string — the "canonical form" or fingerprint. For example:
"eat"→ sorted →"aet""tea"→ sorted →"aet""ate"→ sorted →"aet"
All three share the key "aet", so they land in the same bucket.
Algorithm
-
Build a hash map from canonical form → list of words that map to it. Iterate through
words, computekey = "".join(sorted(word))for each, and append the word tobuckets[key]. -
Sort within each cluster lexicographically. This satisfies tie-break rule 1.
-
Collect all clusters into a result list, then sort by
cluster[0](the lex-smallest word in each cluster after the inner sort). This satisfies tie-break rule 2.
Correctness
- The sorted-character key is a bijection between anagram equivalence classes and canonical strings, so grouping by this key is both sound (only true anagrams share a key) and complete (all anagrams of a word share its key).
- Because each word belongs to exactly one equivalence class, no word appears in two clusters, and every word appears in exactly one cluster.
- The double sort (inner + outer) produces a unique, deterministic ordering.
Edge Cases
- Empty input
[]: the hash map is empty,resultis[]. Correct. - Single empty string
[""]:sorted("")→[],"".join([])→"". Key is"", cluster is[""]. Correct. - Multiple empty strings: they all share key
""and form one cluster["", "", ""](already sorted). Correct. - Duplicate non-empty strings: duplicates share the same key and are kept together.
- All singletons (no two words are anagrams): each forms its own 1-element cluster.
Complexity
| Time | O(n · L · log L) for sorting each of the n words of length ≤ L, plus O(n log n) for sorting the clusters — dominated by O(n · L · log L). |
| Space | O(n · L) to store all words in the buckets and result. |
With n ≤ 2,000 and L ≤ 50 this is extremely fast in practice.
from typing import List
from collections import defaultdict
def group_anagram_clusters(words: List[str]) -> List[List[str]]:
buckets = defaultdict(list)
for word in words:
key = "".join(sorted(word))
buckets[key].append(word)
result = []
for cluster in buckets.values():
cluster.sort()
result.append(cluster)
# Sort clusters by their lexicographically smallest element (first after inner sort)
result.sort(key=lambda cluster: cluster[0])
return result