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
- If lengths differ, not anagrams
- Count frequency of each char in first string
- Decrement for each char in second string
- All counts should be exactly 0 at the end
Related Data Structures & Algorithms exercises
- Practice Subarray Sum Equals K in Java
- Practice Longest Consecutive Sequence in Java
- Practice Valid Parentheses in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler