Home  Dsa   Group anagr ...

Group Anagrams problem and solution in Java and Python

Let’s go through the Group Anagrams problem — one of the most common interview questions that builds on the Valid Anagram concept.


🧩 Problem: Group Anagrams

Question: Given an array of strings, group the anagrams together.

Example:

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

💡 Intuition

An anagram group means all words that have the same set of letters.

For example:

If two words have the same sorted version, they belong to the same group.


🪜 Approach 1 — Sorting Based Key (Most Common)

🧠 Idea:

Example:

WordSorted KeyGroups
eataet["eat"]
teaaet["eat","tea"]
tanant["tan"]
ateaet["eat","tea","ate"]
natant["tan","nat"]
batabt["bat"]

Java Solution

import java.util.*;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) return new ArrayList<>();
        
        Map<String, List<String>> map = new HashMap<>();
        
        for (String s : strs) {
            char[] ch = s.toCharArray();
            Arrays.sort(ch);
            String key = new String(ch);  // e.g. "aet"
            
            if (!map.containsKey(key))
                map.put(key, new ArrayList<>());
            
            map.get(key).add(s);
        }
        
        return new ArrayList<>(map.values());
    }
}

Python Solution

from collections import defaultdict

def groupAnagrams(strs):
    groups = defaultdict(list)
    
    for word in strs:
        key = ''.join(sorted(word))
        groups[key].append(word)
    
    return list(groups.values())

🧠 Approach 2 — Character Count Key (Optimized)

Sorting each string takes O(k log k) time. If strings are long but have limited characters (like lowercase English letters), we can count characters instead.


⚙️ Idea

Example: "eat"[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0] "tea" → same key → group together!


Java Solution (Counting)

import java.util.*;

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

        for (String s : strs) {
            int[] count = new int[26];
            for (char c : s.toCharArray()) {
                count[c - 'a']++;
            }
            
            String key = Arrays.toString(count);
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
        }

        return new ArrayList<>(map.values());
    }
}

Python Solution (Counting)

from collections import defaultdict

def groupAnagrams(strs):
    groups = defaultdict(list)
    
    for word in strs:
        count = [0] * 26
        for c in word:
            count[ord(c) - ord('a')] += 1
        groups[tuple(count)].append(word)
    
    return list(groups.values())

⚖️ Complexity

ApproachTime ComplexitySpace ComplexityNotes
Sorting keyO(n * k log k)O(n * k)Easy and clean
Count keyO(n * k)O(n * k)Faster for long strings

🌍 Real-World Analogy

Imagine a dictionary shelf 🧾:


Published on: Oct 11, 2025, 10:03 PM  
 

Comments

Add your comment