Leet Code

#11. Group Anagrams

brian | Published: Feb. 12, 2025, 2:50 p.m. | Updated: May 25, 2025, 4:04 p.m.

Profile Picture

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

 

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

'''
from typing import List
from collections import defaultdict

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

        for s in strs:# this loops the entire list
            count = [0] * 26 #a - z -> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            for c in s:# this loops the word
                count[ord(c) - ord("a")] += 1
                # print(count)
            #for example the first ["eat"] is(1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)
            #if that key does not exist it will create one because of defaultdict, but if it does exist (that means its an anagram because same keys)
            # defaultdict(<class 'list'>, {(1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0): ['eat', 'tea', 'ate'],
            #then it will append the word -> 's' in this case is the full word.
            # it works just like default dict
            res[tuple(count)].append(s) # is where the actual grouping of anagrams happens.
            # we convert the count list into a tuple. Tuples are immutable and hashable, making them suitable as dictionary keys.
        return res.values()

if __name__ == "__main__":
    strs = ["eat","tea","tan","ate","nat","bat"]
    obj1 = Solution()

    print(obj1.groupAnagram(strs))



#>> dict_values([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']])