Skip to content

47. Group Anagrams

Difficulty: Medium · Topic: DSA for data engineers

Write group_anagrams(words): group the words that are anagrams of each other (the same letters in a different order). Return a list of groups:

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

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

Expected: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Hints

Hint 1Two words are anagrams exactly when their sorted letters are equal.
Hint 2Use ''.join(sorted(word)) (or a letter-count tuple) as a dict key.
Hint 3Dicts keep insertion order, so the groups come out in first-appearance order.

Learn the concepts

More Python problems

All Python problems