Group Anagrams LeetCode Solution

Here, We see Group Anagrams LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Group Anagrams LeetCode Solution

Group Anagrams LeetCode Solution

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

Group Anagrams Leetcode Solution C++

class Solution {
    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());
        vector<vector<string>> anagrams;
        for (auto p : mp) { 
        return anagrams;
Code language: C++ (cpp)

Group Anagrams Leetcode Solution 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();
            String str=new String(arr);
                map.put(str,new ArrayList<>());
        return new ArrayList<>(map.values());       
Code language: Java (java)

Group Anagrams Leetcode Solution 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);
Code language: JavaScript (javascript)

Group Anagrams Leetcode Solution 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]
                hashmap[key] += [st]
        return hashmap.values()
Code language: Python (python)
Scroll to Top