49. Group Anagrams LeetCode Solution

In this guide we will provide 49. Group Anagrams LeetCode Solution with best time and space complexity. The solution to Group Anagrams problem is provided in various programming languages like C++, Java and python. This will be helpful for you if you are preparing for placements, hackathon, interviews or practice purposes. The solutions provided here are very easy to follow and with detailed explanations.

Table of Contents

49. Group Anagrams LeetCode Solution image

Problem Statement of Group Anagrams

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

Example 1:

Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Explanation:

There is no string in strs that can be rearranged to form “bat”.
The strings “nat” and “tan” are anagrams as they can be rearranged to form each other.
The strings “ate”, “eat”, and “tea” are anagrams as they can be rearranged to form each other.

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.

Complexity Analysis

  • Time Complexity: O(nk\log k), where n = |\texttt{strs}| and k = |\texttt{strs[i]}|
  • Space Complexity: O(nk)

49. Group Anagrams LeetCode Solution in C++

class Solution {
 public:
  vector<vector<string>> groupAnagrams(vector<string>& strs) {
    vector<vector<string>> ans;
    unordered_map<string, vector<string>> keyToAnagrams;

    for (const string& str : strs) {
      string key = str;
      ranges::sort(key);
      keyToAnagrams[key].push_back(str);
    }

    for (const auto& [_, anagrams] : keyToAnagrams)
      ans.push_back(anagrams);

    return ans;
  }
};
/* code provided by PROGIEZ */

49. Group Anagrams LeetCode Solution in Java

class Solution {
  public List<List<String>> groupAnagrams(String[] strs) {
    Map<String, List<String>> keyToAnagrams = new HashMap<>();

    for (final String str : strs) {
      char[] chars = str.toCharArray();
      Arrays.sort(chars);
      String key = String.valueOf(chars);
      keyToAnagrams.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
    }

    return new ArrayList<>(keyToAnagrams.values());
  }
}
// code provided by PROGIEZ

49. Group Anagrams LeetCode Solution in Python

class Solution:
  def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
    dict = collections.defaultdict(list)

    for str in strs:
      key = ''.join(sorted(str))
      dict[key].append(str)

    return dict.values()
#code by PROGIEZ

Additional Resources

See also  47. Permutations II LeetCode Solution

Feel free to give suggestions! Contact Us