Group Anagrams
Python data engineering interview problem. Difficulty: beginner. Pattern: Hashing. About 10 minutes. Free to practice.
Group strings that are anagrams; sort groups and group order. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Anagrams are words made of the same letters in a different order. 'eat', 'tea' and 'ate' are anagrams of each other. Search tools group such words together. Write a function group_anagrams(strs) that takes a list of words and groups the words that are anagrams of each other. Return a list of groups, where each group is a list of words. To make the output predictable, sort the words inside every group from A to Z, and then sort the groups by their first word. For ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] the answer is [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]. Keep the print lines in the editor.
Requirements
- Put words with exactly the same letters into the same group.
- A word with no anagram partner forms a group on its own.
- Sort the words inside each group alphabetically.
- Sort the groups by the first word of each group.
Constraints
- Words are lowercase letters.
- Return a list of lists of words.
- Every input word appears in exactly one group.
Examples
Input: group_anagrams(['eat','tea','tan','ate','nat','bat']) Output: [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']] Groups keyed by sorted letters.
Topics: lakebench, python, anagram, grouping.
More Python interview questions · All interview problems · Learn data engineering
Group Anagrams
Interview-style drill: Group strings that are anagrams; sort groups and group order.
Implement `group_anagrams(strs: list[str]) -> list` grouping anagrams. Within each group, sort strings ascending. Sort groups by their first element. Example: `['eat','tea','tan','ate','nat','bat']` → `[['ate','eat','tea'],['bat'],['nat','tan']]`. Keep the harness.