Group Anagrams LeetCode – Python Solutions

LeetCode has a Medium coding Problem in Its’ Algorithm Section “Group Anagrams LeetCode”. Today We are going to solve this problem in Python. LeetCode Link of the Problem is HERE


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.


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


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

Solution to Group Anagrams LeetCode

class Solution(object):
    def groupAnagrams(self, strs):
        :type strs: List[str]
        :rtype: List[List[str]]
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
        return ans.values()


Runtime: 84 ms, faster than 86.54% of Python online submissions for Group Anagrams.

Memory Usage: 19.6 MB, less than 24.73% of Python online submissions for Group Anagrams.


Python-related posts Visit HERE

C++ related posts Visit HERE

Databases related posts Visit HERE

Data Structures related posts visit HERE

Algorithms related posts visit HERE

Data Science related posts visit HERE

Share the Knowledge