call(back)
Algorithms & Data StructureseasySign in to star problems

Group Anagrams

Group the anagrams in a list of lowercase words. Return the groups with each group sorted ascending and the groups ordered by their first word.

groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
  ->  [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]

Duplicates stay in their group.

Hints

Hint 1

Anagrams share a canonical key. Sorting each word gives one in O(L log L); a 26-slot letter count gives one in O(L).

Hint 2

Bucket words by key in a map, then sort inside each bucket and sort the buckets by first element for deterministic output.

Asked at