Skip to content

visual walkthrough

Group Anagrams

MediumHash Map GroupingReported at: AmazonMicrosoftMeta+15

Choosing a good hash key (sorted string or count tuple) is the whole problem.

Solve on LeetCode

The idea

Anagrams are the same letters in a different order, so sorting the letters gives every member of a family the same "fingerprint". Use that fingerprint as a key in a hash map and the groups assemble themselves.

Comparing every pair of words works too, but repeats a lot of work.

Complexity

approachtimespace
Compare wordsO(n² · k log k)O(n)
Sorted-letters keyO(n · k log k)O(n)

More walkthroughs