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.
Examples
Example 1
`strs = ["eat", "tea", "tan", "ate", "nat", "bat"]``[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]`Any order of groups, and of words inside a group, is accepted.
Example 2
`strs = [""]``[[""]]`Example 3
`strs = ["a"]``[["a"]]`Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
Hints
Hint 1
"Group" means you return a list of lists. Neither the order of the groups nor the order inside a group matters.
Hint 2
"Put equivalent items together" means building a canonical key and grouping by it.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
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).
Alternative. 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.
Complexity
- Time
- O(n · k log k)
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.
- Space
- O(n · k)
Code
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]]
}
}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.
Interview script
"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)."
Source: LeetCode 49: Group Anagrams Source: Java SE 17 API: Map.computeIfAbsent) Source: [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))
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))