This page looks best with JavaScript enabled

Group Anagrams

 ·  ☕ 1 min read  ·  ✍️ Syed Dawood

Problem

LeetCode 49: Group Anagrams

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
        res = defaultdict(list)

        for i in strs:
            key = "".join(sorted(i))
            res[key].append(i)
        return list(res.values())

Explaination

We loop over list of strings. Sort string and use as key for our dict to group anagrams

References

Also see

Share on

ALLSYED
WRITTEN BY
Syed Dawood
< frontend | backend | fullstack > Developer