CodingNodes / Arrays & Hashing / Group Anagrams System design Space play · ←→ step · R restart

Problem

You get a list of lowercase words strs. Two words are anagrams if one can be rearranged into the other.

Put the words into groups so that each group holds exactly the words that are anagrams of one another. Return all the groups. The order of the groups and the order inside a group do not matter.

Constraints

  • 1 ≤ strs.length ≤ 10000
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] uses only lowercase letters a to z

Examples: pick one to animate

Solutions

TimeO(n · k log k) SpaceO(n · k)

Time: Each of the n words has up to k letters, and sorting a word costs k log k.

Space: The map stores every word once, plus a sorted key of up to k letters per group.

Anagrams become the same string once their letters are sorted. Use that sorted string as a map key and collect the original words under it.