Instagram
youtube
Facebook
Twitter

Group Anagrams Leetcode Solution

In this tutorial, we are going to solve a leetcode problem, Group Anagrams in python. 

Task:

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

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


Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Solution:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        if len(strs) == 0:
            return [strs]
        elif len(strs) == 1:
            return [strs]
        dct = {}
        for i in range(len(strs)):
            sorted_ = "".join(sorted(strs[i]))
            if sorted_ not in dct.keys():
                dct[sorted_] = [strs[i]]
            else:
                dct[sorted_].append(strs[i])
        return dct.values()

Steps:

step1: First we added the base case for the problem.

step2: then, we initiated an empty dictionary and looped through the strs.

step3: then, we created a string sorted_ which join the sorted strs[i].

step4: Now, we add the sorted_ string into the dictionary as key and strs[i] as its value.

step5; then we return the values of dct as our final answer.