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
Example 1
Output: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
Example 2
Output: [[""]]
Example 3
Output: [["a"]]
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 a1e1t1a1n1t1a1b1t1
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.
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[eat, tea, ate]a1n1t1a1b1t1
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 a1b1c1d1
Keeping the groups
Where does each word go once its key is known? A HashMap
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
- First, create
, agroups from each key to the list of words that have that key.HashMap - Go through the words with a loop. For each word
, the helper methods builds its key. Inside it, the arraykey(s) holds 26 counters, andcount adds one to the counter for lettercount[c - 'a']++ .c - Still inside
, akey namedStringBuilder walks the 26 counters and appends each letter whose count is above 0, followed by its count.sb - Back in the loop,
returns the list for that key. The first time a key appears, it creates an empty list and stores it. Thengroups.computeIfAbsent(key(s), k -> new ArrayList<>()) is added to that list.s - After the last word, the map's values are the groups, so return
.new ArrayList<>(groups.values())
The main
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:
[[bat], [tan, nat], [eat, tea, ate]]
[[]]
[[a]]
[[abb, bab], [aab, aba]]
[[, ], [ab], [cd]]
Look at the first line: [bat][tan, nat][eat, tea, ate]HashMap
The second line, [[]]
On the fourth line, "aab" and "abb" both use only the letters a and b, but in different amounts. Their keys are a2b1a1b2[abb, bab][aab, aba]
The last line starts with [, ]key11
The original implementation,
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,
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).key - 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