LeetCode 49. Group Anagrams

Description

https://leetcode.com/problems/group-anagrams/

Given an array of strings, group anagrams together.

Example:

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

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Explanation

use sorted words to group

Python Solution

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        result = []
        
        groups = {}
        
        for word in strs:
            sorted_word = ''.join(sorted(word))
            if sorted_word in groups:
                groups[sorted_word].append(word)
            else:
                groups[sorted_word] = [word]
        
        for key, value in groups.items():
            result.append(value)
            
        return result
  • Time complexity: O(n).
  • Space complexity: O(n).

2 Thoughts to “LeetCode 49. Group Anagrams”

Leave a Reply

Your email address will not be published. Required fields are marked *