Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-060

Group Anagrams

Problem

Group words that are anagrams of one another and return the groups as a list of lists.

Iterate the words in order and bucket each into a dictionary keyed by its sorted characters, so groups appear in order of first occurrence and words keep their input order.

Hint

Two words are anagrams exactly when their sorted character sequences match.

Test cases

case 1
in: [["eat","tea","tan","ate","nat","bat"]]
expected: [["eat","tea","ate"],["tan","nat"],["bat"]]
case 2
in: [[""]]
expected: [[""]]
case 3
in: [["a"]]
expected: [["a"]]
case 4
in: [["ab","ba","abc","cba","bac"]]
expected: [["ab","ba"],["abc","cba","bac"]]
Starter codePython
def group_anagrams(words):
    # Your code here
    pass

4 test cases · run your code against them in the editor