Notes

Personal notes on various topics

View on GitHub

Intuition

To group anagrams, we need a way to identify strings that are anagrams of each other. Counting the frequency of each character provides a unique signature for each group of anagrams.

Approach

Complexity

Code

from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        from collections import defaultdict

        ans = defaultdict(list)

        for s in strs:
            cnt = [0] * 26
            for c in s:
                cnt[ord(c) - ord("a")] += 1

            ans[tuple(cnt)].append(s)

        return list(ans.values())

Back to Problem Statement