Ecommet

Group Anagrams

Medium Problem 8 of 151 Java and Python

Problem

Given an array of strings strs, group the anagrams together. Return the groups in any order.

Two words are anagrams if they contain the same letters the same number of times.

Example 1

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

Example 2

Input
strs = [""]
Output
[[""]]

Constraints

  • 1 ≤ strs.length ≤ 10⁴
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] contains only lowercase English letters.

Explanation

Anagrams look different but share a signature. Give every word a key that is identical for all its anagrams, then group words by that key in a hash map.

Two good keys: the word with its letters sorted ("eat" → "aet"), or its 26 letter counts. Counting avoids the sort for each word.

Approach 1 · Better

Sorted word as the key

  • Time O(n · k log k), k = longest word
  • Space O(n · k)

Sort each word's letters and use the result as the map key.

  1. For each word, sort its characters to get key.
  2. Append the word to groups[key].
  3. Return the map's values.
Java
import java.util.*;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groups = new HashMap<>();
        for (String word : strs) {
            char[] letters = word.toCharArray();
            Arrays.sort(letters);
            String key = new String(letters);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
        }
        return new ArrayList<>(groups.values());
    }
}
Python
from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)
        for word in strs:
            groups["".join(sorted(word))].append(word)
        return list(groups.values())

Approach 2 · Optimal

Letter counts as the key

  • Time O(n · k)
  • Space O(n · k)

Count the 26 letters of each word. The tuple of counts is the same for all anagrams, and building it takes O(k) instead of O(k log k).

  1. For each word, count how many times each letter a–z appears.
  2. Turn the counts into a key (a tuple in Python, a string such as "1#0#2#…" in Java).
  3. Group words by that key.
Java
import java.util.*;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groups = new HashMap<>();
        for (String word : strs) {
            int[] count = new int[26];
            for (char c : word.toCharArray()) {
                count[c - 'a']++;
            }
            StringBuilder key = new StringBuilder();
            for (int c : count) {
                key.append(c).append('#');
            }
            groups.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(word);
        }
        return new ArrayList<>(groups.values());
    }
}
Python
from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        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 compared

ApproachTimeSpace
Better Sorted word as the keyO(n · k log k), k = longest wordO(n · k)
Optimal Letter counts as the keyO(n · k)O(n · k)

Key takeaways

  • Grouping problems become hash map problems once you find a key that equal items share.
  • Separate the counts with a delimiter in the string key, or [1, 11] and [11, 1] would collide.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem