1. Canonical key
Sorting a word gives every anagram the same signature.
const key = str.split("").sort().join("")Typorithm · medium
Step 1 of 8 · intro card
Arrays & Hashing
Use a sorted-letter signature as the key so all anagrams of a word share one bucket.
Anagrams differ only in order, so sorting a word produces a shared canonical key.
A Map from key to a list collects every word with that signature.
The final answer is just the Map's value lists.
Sorted letters = canonical key.
Map key → list of words.
Anagrams share a bucket.
function groupAnagrams(strs) {
const groups = new Map();
for (const str of strs) {
const key = str.split("").sort().join("");
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(str);
}
return [...groups.values()];
}Connect each part of the code to the concept before you type.
Sorting a word gives every anagram the same signature.
const key = str.split("").sort().join("")Create a list the first time a signature appears.
if (!groups.has(key))All words with the same key land in one group.
groups.get(key).push(str)Spread the Map's value lists into the result array.
return [...groups.values()]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.