MediumNo. 0049

Group Anagrams — LeetCode 49 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, String, Sorting
Reading time
2 min

The problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Python solution

PythonSolution
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        d = defaultdict(list)
        for s in strs:
            k = ''.join(sorted(s))
            d[k].append(s)
        return list(d.values())

Complexity

Time
O(n × k × log k)where n and k are the lengths of the string array and the maximum length of the string, respectively
Space · auxiliary
O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 49. Group Anagrams is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 49. Group Anagrams?

LeetCode 49. Group Anagrams is rated Medium on LeetCode.

What is the time complexity of LeetCode 49. Group Anagrams?

The Python solution on this page runs in O(n × k × log k), where n and k are the lengths of the string array and the maximum length of the string, respectively.

What is the space complexity of LeetCode 49. Group Anagrams?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 49. Group Anagrams cover?

LeetCode 49. Group Anagrams is tagged Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.