Hashmap / Set

Hashmap (sidekick)

Signal

Seen-before, count frequencies, group by key, deduplicate

Template

Trade space for O(1) lookups.

Worked example (1)

#20

Hashmap Grouping

Hashmap

Group a list of words so that anagrams of each other are in the same group.

function groupAnagrams(strs: string[]): string[][] {
  const groups = new Map<string, string[]>();
  for (const word of strs) {
    const key = [...word].sort().join(''); // canonical form = sorted letters
    const bucket = groups.get(key);
    if (bucket) bucket.push(word);
    else groups.set(key, [word]);
  }
  return [...groups.values()];
}
Insight

Anagrams share one canonical key; the map does the grouping in a single pass.