Group Anagrams

12 May 2026 0 Likes

Problem Description

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

Two strings are considered anagrams if they contain the same characters with the same frequencies, but the arrangement of characters may differ.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation: The strings "eat", "tea", and "ate" are anagrams of each other because they contain identical characters with the same frequencies.
Example 2:
Input: strs = [""]
Output: [[""]]
Explanation: The array contains a single empty string, so it forms its own group.
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Explanation: Since there is only one string, it becomes a single anagram group.

Constraints

The array contains at least 1 string. Each string contains only lowercase English letters.

The length of each string and the total number of strings may vary depending on platform limits. The output should contain groups where all strings inside the same group are valid anagrams of each other.

An efficient solution is expected to minimize repeated string comparisons and use efficient grouping techniques.

Understanding the Problem

The problem is asking us to place all strings that are anagrams of each other into the same group.

A simple way to understand the problem is by comparing every string with all other strings and checking whether they contain the same characters with identical frequencies.

For example: "eat", "tea", and "ate"

All three strings contain:

a → 1 time
e → 1 time
t → 1 time

Since their character frequencies are identical, they belong to the same group.

On the other hand: "tan" and "nat" also form another valid anagram group because both contain the same characters.

The main challenge is finding an efficient way to identify which strings belong together without repeatedly comparing every pair of strings.

Hints

The first hint is to think about what remains identical for all anagrams even if the order of characters changes.

One important observation is that sorting anagrams always produces the same string. For example:

"eat" → "aet"
"tea" → "aet"
"ate" → "aet"

This sorted string can be used as a unique identifier for grouping anagrams.

A HashMap can help efficiently store groups where:

Key → sorted string
Value → list of anagrams

Solutions

OPTIMAL

HashMap with Sorted String Key Solution

This approach uses a HashMap to group all strings that are valid anagrams of each other.

The main observation is that if two strings are anagrams, then after sorting their characters, both strings become identical.

For example:

"eat" → "aet"
"tea" → "aet"
"ate" → "aet"

Since all three strings produce the same sorted result, they belong to the same anagram group.

We use the sorted string as the key inside the HashMap and store all matching anagrams inside a list associated with that key.

For every string:

1. Convert it into a character array
2. Sort the characters
3. Convert the sorted array back into a string
4. Store the original string inside the corresponding group

Finally, all grouped values from the map are returned as the result.

This approach efficiently groups anagrams while avoiding repeated pair comparisons.
public class A_Map {

    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[] ca = s.toCharArray();

            Arrays.sort(ca);

            String key = String.valueOf(ca);

            map.computeIfAbsent(
                    key,
                    k -> new ArrayList<>()
            ).add(s);
        }

        return new ArrayList<>(map.values());
    }
}
from collections import defaultdict

class Solution:

    def groupAnagrams(self, strs):

        mp = defaultdict(list)

        for s in strs:

            key = ''.join(sorted(s))

            mp[key].append(s)

        return list(mp.values())
Time Complexity
O(n × k log k)

Where:
n = number of strings
k = average length of each string
Space Complexity
O(n × k)

Conclusion

The Group Anagrams problem is an important string and hashing problem that teaches how to efficiently classify strings based on shared characteristics.

The problem introduces the practical use of HashMaps, sorting, and frequency-based grouping techniques.

Mastering this problem helps build a strong understanding of string manipulation, hash-based grouping, and pattern recognition, which are frequently used in coding interviews and real-world applications.

💬 Comments