awelgorithms

Group Anagrams: the skills you need first

Updated

LeetCode · medium · hash maps. The anagram key is the grouping key. Do not overwrite the list under it.

open on LeetCode

Skills this problem builds on

Stuck on Group Anagrams? It is usually one of these. Get each one solid and the solution stops being a trick.

  1. Group values by a key

    Grouping is key → list of items with that key. First time you see the key, put an empty list (or a one-item list). Later items append. The key is unique. The list grows.

  2. Append to a list under a key

    The mutation is: if absent, put key → [x]; else values.get(key).append(x). Do not put key → [x] on a later item. That overwrite drops the old list.

  3. Build a frequency map

    A frequency map is value → count. One pass: for each x, put x → getOrDefault(x,0)+1. Unseen keys are absent (count 0), not stored as zeros.

check which ones you have 10 minutes, free, no account.

More hash maps problems