Typorithm · medium

Group Anagrams

group-anagramsarrays-hashingcanonical-keybucketinghash-map
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Group Anagrams

0%

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.

01

Sorted letters = canonical key.

02

Map key → list of words.

03

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()];
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Canonical key

Sorting a word gives every anagram the same signature.

const key = str.split("").sort().join("")

2. New bucket

Create a list the first time a signature appears.

if (!groups.has(key))

3. Add to bucket

All words with the same key land in one group.

groups.get(key).push(str)

4. Collect groups

Spread the Map's value lists into the result array.

return [...groups.values()]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Group Anagrams: Lesson & Practice · Typorithm | ApplyDjinn