LeetSolved

Find solutions to all LeetCode problems here.

49.

Group Anagrams

Medium

Problem Description

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

Examples

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

Input: strs = ['']
Output: [['']]

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

Constraints

Approach to Solve

Use a hash map to group anagrams by their sorted form.

Code Implementation

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = defaultdict(list)
        for word in strs:
            sorted_word = ''.join(sorted(word))
            anagrams[sorted_word].append(word)
        return list(anagrams.values())

Explanation

This solution uses a hash map to group anagrams by their sorted form. Here's a detailed explanation of the algorithm:

  1. Initialize an empty hash map to store the groups of anagrams.
  2. Iterate through each string in the input list strs:
    • Sort the characters of the string.
    • Use the sorted string as the key in the hash map.
    • Add the original string to the list associated with this key.
  3. After processing all strings, the hash map will contain all anagrams grouped by their sorted forms.
  4. Return the values of the hash map as a list of lists of strings.

The time complexity is O(N * K log K), where N is the number of strings and K is the maximum length of a string in strs. This is because for each string, we sort it, which takes O(K log K) time, and we do this for N strings. The space complexity is O(N * K) to store the groups of anagrams in the hash map.

Complexity

  • Time Complexity: O(N * K log K), where N is the number of strings and K is the maximum length of a string in strs.
  • Space Complexity: O(N * K)
Code copied to clipboard!