Group Anagrams — LeetCode 49 Python Solution

MediumArrayHash TableStringSorting
Problem
#49
Pattern
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

Python
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

MeasureComplexity
TimeO(n\times k\times \log k), where n and k are the lengths of the string array and the maximum length of the string, respectively
SpaceO(n) auxiliary

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

On study lists

This problem is on Blind 75, NeetCode 150 and Top Interview 150.

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\times k\times \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.

Get Stealth Interview