Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

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