PythonStudio
Interview Problems

Group Anagrams

medium · hashmap

You are given a list of strings `strs`. Two strings are anagrams of each other if they contain exactly the same letters, each appearing the same number of times, just in a different order. Split the list into groups so that every group holds strings that are all anagrams of each other, and no two groups share an anagram. Input: `strs` (a list of strings). Output: a list of groups. Return the groups in the order their first member appears in the input, and keep the input order of the strings inside each group. Example: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] -> [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].

Starter code

def group_anagrams(strs: list[str]) -> list[list[str]]:
    """Group strings that are anagrams of each other."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler