ThinkinMonke
HomeBlogsAbout
HomeBlogAbout
    Blog
    DSA Walkthrough - 04

    Table of Contents

    DSA Walkthrough - 04

    Walkthrough of the problem "Group Anagrams"

    January 18, 2026
    2 min
    Article
    DSA
    LeetCode
    Set
    Array
    Python
    DSA Walkthrough - 04
    Algorithm

    Table of Contents

    Intro

    • The problem is, a bunch of strings will be give in an array, we need to we need to group the anagrams together.
    • This is a both grouping and anagram problem

    First approach

    • My first approach was the classic hashmap approach, we store them together with their count and print them.
    • What i thought at first was that we can check the len of the words present and if they are same then we can say that the given word is an anagram
    • The major different between this and the regular anagram problem is that in regular anagram we just return the bool if the given word is an anagram.
    • But in here, we cant do that as the list may contain the same len of letters but they can be any different alphabets.
    • Therefore with the help of my close friend (ChatGPT), I was able to figure out that we cant really compare the len, instead we sort them individually and store them in the hashmap.

    Solution

    • The solution goes pretty much like this,.
    • we create an hashmap, we loop through the array.
    • We then sort every str from strs and join them to form the sorted word
    • Now we use the sorted word as the key for the hash and the original str become the values of the hash
    • we can use dictionarydict in python that automatically creates key and empty value when the key is absent
    • Or we can create the key manually by using the if statements.
    • in the end we return them as list of hash values

    Code

    
    class Solution:
    
        def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
    		hsh = {}        
            for s in strs:
                key = ''.join(sorted(s))
                if key not in hsh:
    	            hsh[key] = []
                hsh[key].append(s)
                
            return list(hsh.values())
    

    Conclusion

    This was a fun problem to solve and as simple as it seems, it was a problem to think and solve.

    Published on January 18, 2026

    Estimated reading time: 2 minutes

    Share this article:

    Series: DSA Walkthrough

    Part 4 of 7
    Back to all posts

    You Might Also Like

    DSA Walkthrough - 05
    Algorithm
    2 min

    DSA Walkthrough - 05

    Walkthrough of the problem "Top K frequent Elements"

    Read more
    DSA Walkthrough - 03
    Algorithm
    1 min

    DSA Walkthrough - 03

    Walkthrough of the problem "Contains Duplicate"

    Read more
    DSA Walkthrough - 02
    Algorithm
    2 min

    DSA Walkthrough - 02

    Walkthrough of the problem "Search in Rotated Sorted Array"

    Read more

    Table of Contents