The 30 second answer
I give every word a canonical key that is the same for all its anagrams, then group words by that key in a HashMap. The simplest key is the word's sorted characters. A faster key is the 26 letter counts joined into a string, which avoids sorting each word. computeIfAbsent creates each group the first time I see its key.
Problem Given a list of words, return the words grouped so that each group holds words that are anagrams of each other. Any group order is accepted. Original: LeetCode 49: Group Anagrams.
Understanding the prompt "Group" means you return a list of lists. Neither the order of the groups nor the order inside a group matters.
Pattern recognition "Put equivalent items together" means building a canonical key and grouping by it.
Brute force Compare each word with every existing group using an anagram check. That is O(n² · k) for n words of length k.
Optimal Key = the sorted characters, at O(k log k) per word. You can also use a count key at O(k) per word. Then map.computeIfAbsent(key, ...).add(word).
Alternatives Count signature: build a string like #1#0#2... from the 26 counts. The separators matter, because without them two different count arrays could produce the same text.
Java solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class GroupAnagrams {
static List<List<String>> groupAnagrams(String[] words) {
var groups = new HashMap<String, List<String>>();
for (var w : words) {
var chars = w.toCharArray();
Arrays.sort(chars);
groups.computeIfAbsent(new String(chars), k -> new ArrayList<>()).add(w);
}
return new ArrayList<>(groups.values());
}
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"})); // [[a]]
}
}Complexity O(n · k log k) time with the sorted key, or O(n · k) with a count key. O(n · k) space for the map.
Edge cases
- The empty string forms its own group.
- A single word.
- All words are anagrams of each other, giving one group.
Follow-ups
- Unicode words: the sorted-char key still works on code points, but the 26-count key doesn't.
- Return the groups sorted: sort each group, then sort the groups by their first word.
Tests ["eat","tea","tan","ate","nat","bat"] gives three groups: {eat,tea,ate}, {tan,nat}, {bat}. [""] gives [[""]]. ["a"] gives [["a"]].
How to say it in the interview "I map each word to a canonical key, its sorted letters, and group words in a hash map with computeIfAbsent. That's O(n·k log k). If they push on speed, I use a letter-count key instead, which is O(n·k)."
Sources (3)
- LeetCode 49: Group Anagramsleetcode.com
- Java SE 17 API: Map.computeIfAbsentdocs.oracle.com
- [Java SE 17 API: Arrays.sort(char[])](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#sort(char%5B%5D))