LeetCode 49: Group Anagrams is a Medium hashmap problem. This Python walkthrough develops a canonical frequency key solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Hashmap |
| Reusable pattern | canonical frequency key |
| Complexity | O(total characters) time and O(total characters) output space |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, convert each word into a 26-count tuple and group words sharing that immutable signature. The invariant worth writing beside the code is: Words share a group exactly when their character-count signatures match.
Step-by-step algorithm
- Identify the input state consumed by
groupAnagrams(strs)and initialize the data required by the canonical frequency key pattern. - Convert each word into a 26-count tuple and group words sharing that immutable signature.
- After each update, verify the page’s central invariant: Words share a group exactly when their character-count signatures match.
- Finish only after the boundary behavior is covered: Empty strings share the all-zero signature; repeated words remain repeated outputs.
Python solution
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs):
groups = defaultdict(list)
for word in strs:
counts = [0] * 26
for char in word: counts[ord(char) - ord("a")] += 1
groups[tuple(counts)].append(word)
return list(groups.values())Reading the implementation
The main entry point is groupAnagrams(strs). The named working state includes groups, counts; those variables make the canonical frequency key state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, convert each word into a 26-count tuple and group words sharing that immutable signature.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Convert each word into a 26-count tuple and group words sharing that immutable signature. Each update records the current item without invalidating earlier decisions; consequently, words share a group exactly when their character-count signatures match.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(total characters) time and O(total characters) output space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert sorted(sorted(group) for group in Solution().groupAnagrams(["eat","tea","tan","ate","nat","bat"])) == [["ate","eat","tea"],["bat"],["nat","tan"]]Common mistakes and edge cases
- Problem-specific boundary: Empty strings share the all-zero signature; repeated words remain repeated outputs.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that words share a group exactly when their character-count signatures match.
Interview review checklist
- Explain why canonical frequency key matches the structure of this input.
- State the invariant in one sentence before tracing code: Words share a group exactly when their character-count signatures match.
- Derive O(total characters) time and O(total characters) output space from how many times each element or state is visited.
- Test the boundary explicitly: Empty strings share the all-zero signature; repeated words remain repeated outputs.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 242. Valid Anagram · Next: 1. Two Sum