Use character-frequency signatures to group anagrams with a hash map.
Use the editor below to group words that contain the same character counts.
Preserve the group and word order
Preserve the order in which each group first appears and the input order inside each group. Repeated characters and empty strings need stable signatures too.
Submit your implementation when it passes the examples.
Given an array of lowercase strings, group the strings that are anagrams of one another.
Return groups in the order their character signature first appears, and keep words inside each group in input order.
1 ≤ words.length ≤ 10,000Results appear here after a run.
Build a 26-position frequency signature for each word. Anagrams produce the same signature even when their characters appear in a different order.
For the input ["eat", "bat", "tea"], compare four slots of the signature. Every unlisted slot is zero.
| Word | a | b | e | t |
|---|---|---|---|---|
eat | 1 | 0 | 1 | 1 |
bat | 1 | 1 | 0 | 1 |
tea | 1 | 0 | 1 | 1 |
Use the full signature as the map key. Create a group when a signature first appears. When the same signature returns, append the word to its existing group. This preserves both the group order and the order within each group.
function groupAnagrams(words) {
const groups = new Map();
for (const word of words) {
const counts = Array(26).fill(0);
for (const character of word) {
counts[character.charCodeAt(0) - 97]++;
}
const signature = counts.join("#");
if (!groups.has(signature)) {
groups.set(signature, []);
}
groups.get(signature).push(word);
}
return Array.from(groups.values());
}Let n be the number of words, L their combined length and g the number of distinct groups. The alphabet has a fixed size of 26.
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n + L) average | Initialize the fixed-size counters for each word and visit every letter. Even an empty word needs a group lookup. |
| Returned groups | O(n + g) references | Each word appears once, in one group. The strings themselves are reused. |
| Auxiliary space | O(g) fixed-size count tuples in Python | JavaScript stores a serialized key per group. If measuring characters, count the combined length of those keys as well. |