codebrew.ai

Group Anagrams

Give every anagram the same canonical key.

Approach

Anagrams share a canonical form — either the sorted string or a 26-length count tuple. Use that form as a hash-map key and append each word to its bucket. The count-tuple key gives O(n·k) versus O(n·k log k) for sorting.

Time complexity

O(n·k)

Space complexity

O(n·k)

Common mistake

Using a mutable list as a dict key — keys must be hashable, so use a tuple or string.

See it run, step by step

Generate an interactive lesson for Group Anagrams — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Group Anagrams

Related problems