Group Anagrams in Java: Explanation & Practice
Group strings that are anagrams of each other
Problem summary
Given an array of strings, group anagrams together. Anagrams are words with same characters rearranged.
Starter code
public class Main {
public static void main(String[] args) {
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
// Key insight: sorted anagram = same string
// Use HashMap<sorted_string, list_of_anagrams>
// Print each group on new line
}
}Expected output and test cases
- Group by sorted form
ate eat tea nat tan bat
- [] → empty
- [a] → just a
a
Hints
- Two anagrams, when sorted, become the same string
- Use sorted string as HashMap key
- Value is list of all strings that sort to that key
- Alternative: use character count array as key
Related Data Structures & Algorithms exercises
- Practice Maximum Subarray (Kadane's Algorithm) in Java
- Practice Two Sum (Unsorted) in Java
- Practice Subarray Sum Equals K in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler