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

  1. Two anagrams, when sorted, become the same string
  2. Use sorted string as HashMap key
  3. Value is list of all strings that sort to that key
  4. Alternative: use character count array as key

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler