Group Anagrams [Medium]

15 Aug 2026, Updated: 20 Sep 2026 2 min read
1
The Group Anagrams problem requires grouping strings that contain the same characters with the same frequencies, even if the characters appear in a different order.

Problem

Given an array of strings strs, group the anagrams together. Two strings are anagrams if they contain the same characters with the same frequencies, but possibly in a different order.

The grouped lists may be returned in any order.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

strs = ["eat","tea","tan","ate","nat","bat"] 

Output

[[eat, tea, ate], [tan, nat], [bat]] 

Solution

This solution uses a HashMap to group words based on a common key.

For each string, its characters are sorted alphabetically to produce a canonical representation. Since all anagrams generate the same sorted string, it can be used as the key in the map.

The HashMap stores a list of strings for each sorted key. As each word is processed, it is added to the corresponding list, and finally all grouped values are returned as the result.
public List<List<String>> groupAnagrams(String[] strs) {
    Map<String, List<String>> group = new HashMap<>();

    for (String s : strs) {
        String key = sort(s);
        group.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
    }

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

private String sort(String s) {
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

Complexity

Let n be the number of strings and k be the maximum length of a string.

Sorting each string takes O(k log k), and this is performed for all n strings, resulting in an overall time complexity of O(n × k log k).

The extra space complexity is O(n × k) for storing the grouped strings and their keys.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion