Problems › Arrays & strings

Group Anagrams

Difficulty: Hard · Topic: Arrays & strings

Given a list of strings strs, group the anagrams together. Return a list of groups; sort each group ascending, and the groups may be in any order. Two words are anagrams iff their sorted characters match — use that as a dictionary key.

Examples

group_anagrams(["eat","tea","tan","ate","nat","bat"])
→ [["ate","eat","tea"],["nat","tan"],["bat"]]
group_anagrams(["a"])
→ [["a"]]

Target complexity: time O(n·k log k), space O(n·k)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Arrays & strings problems