Code Logo

Group Anagrams

Published at23 Jul 2026
Medium 0 views
Like0

Given an array of strings, group the anagrams together. You can return the groups in any order. An anagram is a word formed by rearranging the letters of another word, using all original letters exactly once.

The solution uses a hash map where the key is the sorted version of each string. All anagrams produce the same sorted string, so they end up in the same group. For each string, sort its characters to create the key, add the original string to the map at that key, then return all map values as the result.

This is a classic medium hash table problem that demonstrates how sorted strings can serve as canonical forms for anagrams.

The time complexity is O(n*k*log k) where n is the number of strings and k is the maximum string length. Using a character count array as the key instead of sorted string improves time to O(n*k) but is more complex to implement. The sorted-key approach is simpler and sufficient for most cases.

The alternative approach uses a character count array of size 26 as the key instead of sorting. This improves time complexity to O(n*k) but requires more code. Both approaches are acceptable, with the sorting approach being simpler to implement.

This problem demonstrates how hash maps can group related items using a normalized key. The sorted string serves as a canonical form that all anagrams share. This technique of normalizing data to create a hash key is widely applicable beyond anagrams, such as grouping words by their letter frequency or grouping files by their checksum.

Example Input & Output

Example 1
Input
["a"]
Output
[["a"]]
Explanation

Single character.

Example 2
Input
["eat","tea","tan","ate","nat","bat"]
Output
[["eat","tea","ate"],["tan","nat"],["bat"]]
Explanation

Anagrams grouped by sorted key.

Example 3
Input
[""]
Output
[[""]]
Explanation

Single empty string.

Algorithm Flow

Recommendation Algorithm Flow for Group Anagrams
Recommendation Algorithm Flow for Group Anagrams

Solution Approach

Create a hash map keyed by sorted string. For each word, sort its characters, use as key, push original word. Return all values.

function solution(strs) {
  var map = {};
  for (var i = 0; i < strs.length; i++) {
    var key = strs[i].split('').sort().join('');
    if (!map[key]) map[key] = [];
    map[key].push(strs[i]);
  }
  return Object.values(map);
}

Time O(n*k*log k), Space O(n*k).

Best Answers

java
import java.util.*;
class Solution {
    public List<List<String>> solution(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for (String s : strs) {
            char[] a = s.toCharArray();
            Arrays.sort(a);
            String key = new String(a);
            map.computeIfAbsent(key, k->new ArrayList<>()).add(s);
        }
        return new ArrayList<>(map.values());
    }
}