Group Anagrams in Java: Solution, Explanation & Practice
Group words that are anagrams of each other
Problem summary
Given a list of words, group them by anagrams.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
// Group anagrams together
// Print each group on a line
}
}Expected output and test cases
- Grouped anagrams
[eat, tea, ate] [tan, nat] [bat]
- All anagrams
[abc, bca, cab]
- No anagrams
[a] [b] [c]
Hints
- Sort each word's characters as key
- Use Map<String, List<String>>
- Same sorted chars = anagrams
Validated solution
Reveal Java solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
static String key(String word) { char[] letters = word.toCharArray(); Arrays.sort(letters); return new String(letters); }
public static void main(String[] args) {
String[] words = {"eat", "tea", "ate", "tan", "nat", "bat"};
Map<String, List<String>> groups = new LinkedHashMap<>();
for (String word : words) groups.computeIfAbsent(key(word), ignored -> new ArrayList<>()).add(word);
for (List<String> group : groups.values()) System.out.println(group);
}
}How to approach the problem
Sorting the letters of a word produces the same key for every anagram. A map then collects each original word under that key; LinkedHashMap keeps groups in the order their first word appears.
Approach
- Turn each word into a canonical sorted-letter key.
- Create a group lazily with computeIfAbsent.
- Append the original spelling to its group.
Time and space complexity
Time: O(n * k log k). Space: O(n * k).
Edge cases to test
- An empty string is an anagram only of another empty string.
- Case and punctuation need normalization rules if they should be ignored.
Common mistakes
- Using the unsorted word itself as the map key.
- Printing a HashMap and expecting a deterministic group order.
Follow-up challenge
Use a 26-count signature to avoid sorting lowercase English words.
Related Collections exercises
- Practice Merge K Sorted Lists in Java
- Practice Stack Using Queues in Java
- Practice Sliding Window Maximum in Java
Practice all Collections exercises · Run this idea in the Java compiler