Group anagrams together.
Problem
Given ["eat","tea","tan","ate","nat","bat"], return groups [["eat","tea","ate"],["tan","nat"],["bat"]] in any order.
Approach
Anagrams share a canonical key. Either sort the characters ("aet"), O(k log k) per word, or count letters into a 26-length signature, O(k) per word. Group with a HashMap<String, List<String>>, or with streams groupingBy.
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class GroupAnagrams {
static List<List<String>> group(String[] words) {
Map<String, List<String>> groups = new HashMap<>();
for (String w : words) groups.computeIfAbsent(signature(w), k -> new ArrayList<>()).add(w);
return new ArrayList<>(groups.values());
}
// O(k) key: letter counts, e.g. "1#0#0#...#1#..." for lowercase a-z
private static String signature(String w) {
int[] counts = new int[26];
for (char c : w.toCharArray()) counts[c - 'a']++;
StringBuilder sb = new StringBuilder();
for (int n : counts) sb.append(n).append('#');
return sb.toString();
}
// Stream version with the sorted-letters key
static List<List<String>> groupWithStreams(String[] words) {
return new ArrayList<>(Arrays.stream(words)
.collect(Collectors.groupingBy(w -> {
char[] cs = w.toCharArray();
Arrays.sort(cs);
return new String(cs);
}))
.values());
}
public static void main(String[] args) {
String[] in = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(group(in));
System.out.println(groupWithStreams(in));
}
}Complexity
Counting key: O(n × k) time for n words of length k; O(n × k) space.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you check whether two strings are anagrams?
If the lengths differ, return false; otherwise count characters of the first string up and the second down in an int[26] (or a map for Unicode) and verify all counts are zero. O(n) time, O(1) space for a fixed alphabet. Sorting both and comparing is O(n log n).