Group Anagrams LeetCode Solution

Last updated on March 7th, 2025 at 09:35 pm

Here, we see a Group Anagrams LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Array, Hash Table, Sorting, String

Companies

Amazon, Bloomberg, Facebook, Uber, Yelp

Level of Question

Medium

Group Anagrams LeetCode Solution

Group Anagrams LeetCode Solution

1. Problem Statement

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"]]

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Hashing with Sorting or Frequency Count”. The key idea is to use a hash map (or dictionary) to group strings that are anagrams of each other by generating a unique key for each group.

3. Code Implementation in Different Languages

3.1 Group Anagrams C++

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mp;
        for (string s : strs) {
            string t = s; 
            sort(t.begin(), t.end());
            mp[t].push_back(s);
        }
        vector<vector<string>> anagrams;
        for (auto p : mp) { 
            anagrams.push_back(p.second);
        }
        return anagrams;
    }
};

3.2 Group Anagrams Java

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String,List<String>> map=new HashMap<>();
        
        for(int i=0;i<strs.length;i++){
            String s1=strs[i];
            char[] arr=s1.toCharArray();
            Arrays.sort(arr);
            String str=new String(arr);
            
            if(map.containsKey(str)){
                map.get(str).add(s1); 
            }else{
                map.put(str,new ArrayList<>());
                map.get(str).add(s1);
            }
        }
        return new ArrayList<>(map.values());       
    }
}

3.3 Group Anagrams JavaScript

var groupAnagrams = function(strs) {
    let res = {};
    for (let str of strs) {
        let count = new Array(26).fill(0);
        for (let char of str) count[char.charCodeAt()-97]++;
        let key = count.join("#");
        res[key] ? res[key].push(str) : res[key] = [str];
    }
    return Object.values(res);
};

3.4 Group Anagrams Python

class Solution(object):
    def groupAnagrams(self, strs):
        hashmap = {}
        for st in strs:
            key = ''.join(sorted(st))
            if key not in hashmap:
                hashmap[key] = [st]
            else:
                hashmap[key] += [st]
        return hashmap.values()

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n * k log k)O(n * k)
JavaO(n * k log k)O(n * k)
JavaScriptO(n * k log k)O(n * k)
PythonO(n * k)O(n * k)

where K is the average length of the strings.

  • The code uses a hash map to group anagrams efficiently.
  • The time complexity is O(n * k log k) for C++, Java, and Python, and O(n * k) for JavaScript.
  • The space complexity is O(n * k) for all implementations.

Scroll to Top