hashing · Problem 5 of 5

Group Anagrams

hard
Amazon logoAmazon
Meta logoMeta
Uber logoUber

Group the words in strs so that anagrams end up together. Return the groups sorted by their first element, with each group sorted alphabetically.

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

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

4 cases, 1 hidden
calltypeexpectedresult
groupAnagrams(["eat","tea","tan","ate","nat","bat"])classic[["ate","eat","tea"],["bat"],["nat","tan"]]
groupAnagrams(["abc","def"])no anagrams[["abc"],["def"]]
groupAnagrams([])empty[]
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(n·k log k) for n words of length k
target space
O(n·k)

The sort per word dominates. A character-count key gets it to O(n·k) at the cost of a clumsier key.

Hints

Stuck? Hints open one at a time, each giving a little more away.

3 hints left