Valid Anagram in Java: Explanation & Practice

Check if two strings are anagrams

Problem summary

Given two strings, check if they are anagrams of each other. Use HashMap to count character frequencies.

Starter code

public class Main {
    public static void main(String[] args) {
        String s = "anagram";
        String t = "nagaram";
        
        // Count chars in s, decrement for t
        // All counts should be 0
        // Print: Is anagram: true
    }
}

Expected output and test cases

  • anagram, nagaram
    Is anagram: true
  • rat, car
    Is anagram: false
  • a, a
    Is anagram: true

Hints

  1. If lengths differ, not anagrams
  2. Count frequency of each char in first string
  3. Decrement for each char in second string
  4. All counts should be exactly 0 at the end

Related Data Structures & Algorithms exercises

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