Group Anagrams: $O(n \cdot k)$ Time via Character Frequency Tuples
The standard approach to grouping anagrams sorts each word of length $k$, producing an $O(n \cdot k \log k)$ runtime across $n$ strings.
Because anagrams share the exact same character frequencies, we can bypass sorting entirely. By counting character occurrences into a fixed-size frequency array of 26 integers and converting that array into an immutable hashable key (a tuple or serialized string), we achieve an optimal $O(n \cdot k)$ time complexity.
Key Comparison: Sorting vs. Frequency Hashing
| Dimension | Sorting Each String | Character Frequency Tuple |
|---|---|---|
| Hash Key | Lexicographically sorted string (e.g., "eat" $\rightarrow$ "aet") |
26-element tuple of counts: (1, 0, 0, ..., 1, ..., 1) |
| Per-String Time | $O(k \log k)$ | $O(k + \vert{}\Sigma\vert{}) = O(k + 26) = O(k)$ |
| Total Time | $O(n \cdot k \log k)$ | $O(n \cdot k)$ |
| Alphabet Bound | Independent of alphabet size | Ideal for fixed alphabets (e.g., lowercase English ASCII) |
When strings are long ($k \gg 26$), eliminating the $O(\log k)$ factor yields significant execution speedups.
Algorithmic Breakdown
- Hash Table Setup: Create a hash map where:
- Key: An immutable 26-element integer tuple (or custom hashable array structure) representing frequencies of
'a'through'z'. - Value: A list of strings matching that frequency profile.
- Key: An immutable 26-element integer tuple (or custom hashable array structure) representing frequencies of
- Frequency Count per String ($O(k)$):
- For each string, initialize an array
countof size 26 with zeroes. - Iterate over each character $c$ in the string, incrementing
count[c - 'a'].
- For each string, initialize an array
- Map Insertion ($O(1)$ amortized):
- Convert the 26-element array into a hashable key.
- Append the original string to the corresponding list in the hash map.
- Collect Results: Extract all values from the map into the final grouped collection.
Implementation (Python & C++)
Python Implementation (Immutable Tuple Keys)
In Python, standard lists are mutable and cannot be used as dictionary keys, but an immutable tuple is hashable and fast:
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
# Map: 26-element tuple -> list of anagrams
anagram_map = defaultdict(list)
for s in strs:
# Initialize a 26-slot count for lowercase English letters
count = [0] * 26
for char in s:
count[ord(char) - ord('a')] += 1
# Tuples are immutable and hashable
anagram_map[tuple(count)].append(s)
return list(anagram_map.values())
C++ Implementation (Custom Array Hash / Delimited Key)
In C++, std::array<int, 26> can be serialized or hashed with a custom hash functor in an std::unordered_map:
#include <vector>
#include <string>
#include <unordered_map>
#include <array>
// Custom hash functor for std::array<int, 26>
struct ArrayHasher {
std::size_t operator()(const std::array<int, 26>& arr) const {
std::size_t hash = 0;
for (int count : arr) {
// Standard hash combination technique
hash ^= std::hash<int>()(count) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
return hash;
}
};
std::vector<std::vector<std::string>> groupAnagrams(const std::vector<std::string>& strs) {
std::unordered_map<std::array<int, 26>, std::vector<std::string>, ArrayHasher> anagram_map;
for (const std::string& s : strs) {
std::array<int, 26> freq = {0};
for (char c : s) {
freq[c - 'a']++;
}
anagram_map[freq].push_back(s);
}
std::vector<std::vector<std::string>> result;
result.reserve(anagram_map.size());
for (auto& entry : anagram_map) {
result.push_back(std::move(entry.second));
}
return result;
}
Complexity & Memory Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(n \cdot k)$ | We process $n$ strings. For each string of length $k$, iterating its characters takes $O(k)$ time, and generating/hashing the 26-element key takes $O(26) = O(1)$ time. Total runtime is strictly linear with respect to the total number of characters across all words. |
| Auxiliary Space | $O(n \cdot k)$ | Memory needed to store the grouped strings and the keys in the hash map. Each key is fixed at 26 integer slots ($O(1)$ space per distinct anagram family). |
- Delimiter/Collision Safety: Using numeric counts inside a fixed-length tuple eliminates parsing ambiguities that can occur with naive string concatenations (e.g., distinguishing between 1
'b'and 11'b's is straightforward because each slot index is explicitly fixed).
