Group Words by Character Frequency
StringsAuto-graded · 21 test casesLast updated
Tests hash map construction with canonical keys to partition strings by anagram equivalence
You are given an array of strings. Your task is to partition these strings into groups where each group contains words that are anagrams of one another. Two words are anagrams if they contain exactly the same characters with identical frequencies, regardless of order.
Return the groups as a list of lists. The order of groups in the output and the order of words within each group should match the order in which they first appear in the input.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100- Each string contains only lowercase English letters
- Total length of all strings combined does not exceed
10^5
Examples
Example 1
Input: group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Example 2
Input: group_anagrams([''])
Output: [['']]
Example 3
Input: group_anagrams(['a'])
Output: [['a']]
Hints
Hint 1
Two words are anagrams if and only if sorting their characters produces identical sequences. Can you use this as a grouping key?
Hint 2
A hash map lets you collect all words that share the same canonical form into the same bucket in a single pass
Hint 3
Remember that lists aren't hashable in Python—convert your sorted character sequence to a tuple or joined string before using it as a dictionary key
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that anagrams share an identical multiset of characters. We need a canonical representation that is the same for all anagrams and different for non-anagrams. Sorting the characters of a word produces exactly this property: 'eat', 'tea', and 'ate' all yield ('a', 'e', 't') when sorted.
Build a hash map where each key is a sorted character tuple and each value is the list of words that produce that key. Iterate through the input once, compute the canonical key for each word, and append the word to the corresponding bucket. Finally, extract all the buckets as the output.
Correctness
If two words map to the same key, their sorted character sequences are identical, meaning they have the same characters at the same frequencies—the definition of anagrams. Conversely, if two words are anagrams, sorting both produces the same sequence, so they land in the same bucket.
Each word is processed exactly once and placed in exactly one group, so the result is a complete partition of the input with no duplicates or omissions.
Since Python dictionaries preserve insertion order, groups appear in the order their first member was encountered, and words within each group maintain their input order.
Complexity
Let N be the number of strings, K the maximum string length, and S the total character count across all strings.
Time: O(S log K). Sorting each word of length L takes O(L log L), so the total sorting cost is O(Σ L log L), which is bounded by O(S log K). Dictionary operations (hashing and insertion) are O(L) per word, dominated by sorting.
Space: O(S) to store the canonical keys and output groups.
Alternative: Using a 26-element character frequency tuple as the key reduces time to O(S), since building each key is O(L). For short strings the sorted approach is simpler and performs similarly in practice.
Implementation
from typing import List
def group_anagrams(strs: List[str]) -> List[List[str]]:
groups = {}
for word in strs:
key = tuple(sorted(word))
groups.setdefault(key, []).append(word)
return list(groups.values())