Group Anagrams | LeetCode 49 | Python | Solution

LeetCode 49

If you know how to valid anagram, this one will be easier for you to solve. You can check this to know about it (Valid Anagram).

I assume that you already know how to valid anagram. So, to solve this problem, we do the same thing. But this time, we have to group all the same types of anagrams from the given string array. For that, we will use HashTable.

We know that the sorted version of the two anagrams is the same. That is why we will list all the strings with the same sorted version in a HashTable. If a sorted version of a string exists as a key, we will append that string as a value of that key. Otherwise, create a new entry using the sorted version and the string as a key-value pair. The value will be in a new array.

After that, we will return all values from the HashTable, not keys. Where each value of HashTable contains a group of anagrams. We are allowed to group them in any order. So, we don’t need to think about ordering.

Let’s see the solution in code.

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

        groups = {}
        for string in strs:
            sorted_version = ''.join(sorted(string))
            if sorted_version in groups:
                groups[sorted_version] = [string]
        return groups.values()

I hope you got the idea about the solution.

Happy Coding.
Happy Learning.