Group Anagrams

Put the words made of the same letters into one group, using a key built from each word's letter counts.

Given an array of strings strs, put the words that are anagrams of each other into the same group and return the groups. Two words are anagrams when one uses exactly the same letters as the other, rearranged, like "eat" and "tea". Each word has only lowercase letters a to z. The groups, and the words inside each group, can come in any order.

Example 1
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
Example 2
Input: strs = [""]
Output: [[""]]
Example 3
Input: strs = ["a"]
Output: [["a"]]
Solution

The Idea

Word games are full of anagrams: shuffle the letters of "listen" and you get "silent". In this problem we get a whole list of words and have to sort them into groups, one group for each set of words that are shuffles of each other.

Take Example 1: "eat", "tea", "tan", "ate", "nat" and "bat". Reading them, you can see that "eat", "tea" and "ate" belong together, and so do "tan" and "nat". "bat" has no partner, so it ends up in a group of its own. But how would a program see that? It could check every word against every other word, but that is a lot of checking for a long list. Is there something a word can tell us about itself, without looking at the others?

There is: which letters it has, and how many of each. "eat" has one a, one e and one t. So do "tea" and "ate", because shuffling moves letters around but never adds or removes one. Write that down in a fixed order, letter then count, and "eat" becomes a1e1t1. "tan" becomes a1n1t1, and "bat" becomes a1b1t1.

A label like this, used to look something up, is called a key. Two words get the same key exactly when they are anagrams, so the grouping takes care of itself: every word goes to the group of its key. Look at the picture below.

Each word gets a key from its letter counts. eat, tea and ate all get the key a1e1t1 and form one group; tan and nat get a1n1t1; bat gets a1b1t1 and is a group on its own.

The column labelled words, on the left, is the input, in order. The three highlighted words, "eat", "tea" and "ate", all point to the key a1e1t1, which leads to the group [eat, tea, ate]. "tan" and "nat" share the key a1n1t1, and "bat" is the only word with a1b1t1, so its group holds just one word.

So each word is looked at once, on its own, and never compared with another word.

Solution Approach

Two decisions turn that idea into code: how to write a word's key, and where to keep the groups so that no word has to be compared with another.

Writing the key

What should the key look like? One easy choice is the word's letters in alphabetical order: "eat", "tea" and "ate" all sort to "aet". That works, but sorting a word of k letters takes about k log k steps.

Counting is faster. An array of 26 counters, one for each letter from a to z, is filled in a single pass over the word. Then a second pass over the 26 counters writes each letter that occurs, followed by its count, in alphabetical order. That is how "eat" becomes a1e1t1.

Why write the letter before each count? The counts alone are not enough. "ab" has one a and one b, so its counts read 11. "cd" has one c and one d, and its counts read 11 too, yet the two words share no letters. With the letters in the key, they become a1b1 and c1d1.

Keeping the groups

Where does each word go once its key is known? A HashMap, Java's table from keys to values, maps each key to the list of words that have it. Looking up a key in it takes about the same time however many groups it holds.

Without the map, each new word would have to be compared, letter by letter, with one word from every group found so far. With n words that are all different, that is about n²/2 comparisons. The map replaces all of them with one lookup per word.

Java Solution

The method groupAnagrams works in these steps:

  1. First, create groups, a HashMap from each key to the list of words that have that key.
  2. Go through the words with a loop. For each word s, the helper method key(s) builds its key. Inside it, the array count holds 26 counters, and count[c - 'a']++ adds one to the counter for letter c.
  3. Still inside key, a StringBuilder named sb walks the 26 counters and appends each letter whose count is above 0, followed by its count.
  4. Back in the loop, groups.computeIfAbsent(key(s), k -> new ArrayList<>()) returns the list for that key. The first time a key appears, it creates an empty list and stores it. Then s is added to that list.
  5. After the last word, the map's values are the groups, so return new ArrayList<>(groups.values()).

The main method runs the three examples, then words with the same letters in different amounts, and a list with "ab", "cd" and two empty strings.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupAnagrams {

    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groups = new HashMap<>();
        for (String s : strs) {
            groups.computeIfAbsent(key(s), k -> new ArrayList<>()).add(s);
        }
        return new ArrayList<>(groups.values());
    }

    // Anagrams share the same letter counts, e.g. "eat" and "tea" -> "a1e1t1"
    private static String key(String s) {
        int[] count = new int[26];
        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 26; i++) {
            if (count[i] > 0) {
                sb.append((char) ('a' + i)).append(count[i]);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(groupAnagrams(new String[] {"eat", "tea", "tan", "ate", "nat", "bat"}));
        System.out.println(groupAnagrams(new String[] {""}));
        System.out.println(groupAnagrams(new String[] {"a"}));
        System.out.println(groupAnagrams(new String[] {"aab", "abb", "bab", "aba"}));
        System.out.println(groupAnagrams(new String[] {"ab", "cd", "", ""}));
    }
}

Running it prints:

Output
[[bat], [tan, nat], [eat, tea, ate]]
[[]]
[[a]]
[[abb, bab], [aab, aba]]
[[, ], [ab], [cd]]

Look at the first line: [bat], [tan, nat] and [eat, tea, ate] are the three groups from the picture. Inside each group the words keep the order they came in, while the order of the groups is whatever order the HashMap keeps its keys in, which the problem allows.

The second line, [[]], is Example 2. It holds one group with one word in it, the empty string, and Java prints an empty string as nothing at all. The empty string has no letters, so its key is empty too.

On the fourth line, "aab" and "abb" both use only the letters a and b, but in different amounts. Their keys are a2b1 and a1b2, so they land in separate groups, each with its own anagram: [abb, bab] and [aab, aba].

The last line starts with [, ]: the two empty strings, side by side in one group. "ab" and "cd" stay apart. A version of key that writes only the counts gives 11 for both words, and would put them into one group.

The original implementation, GroupAnagrams.java, is on GitHub.

Complexity

The work is building one key per word, plus one map lookup per word.

  • Time: O(n × k), where n is the number of words and k the length of the longest one. For each word, key counts its k letters and then scans 26 counters. Hashing the finished key costs no more, since the key is never longer than twice the word. Sorting each word's letters for its key instead would cost O(n × k log k).
  • Space: O(n × k), because the map stores every word once, in its group, plus one key per group.

Checking whether just two words are anagrams is Valid Anagram.