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:
- groups ordered by the first appearance of any of their words;
- words inside a group in input order, duplicates kept;
- letters compared exactly (case matters).
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 1
Two words are anagrams exactly when their sorted letters are equal.Hint 2
Use''.join(sorted(word)) (or a letter-count tuple) as a dict key.Hint 3
Dicts keep insertion order, so the groups come out in first-appearance order.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
More Python problems
- Two Sum · Easy
- Valid Brackets · Easy
- First Non-Repeating Character · Easy
- Longest Substring Without Repeats · Medium
- Top K Frequent with a Heap · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard