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 interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. TryGetValueCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.

  2. The GraderCharacter joke · No posting date

    Your solution is correct. Your variable names are a crime scene.

  3. TryGetValueCharacter joke · No posting date

    I found the bug. It was me. I was the bug.