Anagram Check in Java: Solution, Explanation & Practice
Check if two strings are anagrams
Problem summary
Write a program that checks if two strings are anagrams (same characters, different order).
Starter code
public class Main {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent"; // Test case 1
// Check if anagrams
// Print: Are anagrams: <true/false>
}
}Expected output and test cases
- listen/silent are anagrams
Are anagrams: true
- triangle/integral
Are anagrams: true
- hello/world not anagrams
Are anagrams: false
Hints
- Sort both strings and compare
- Or count character frequencies
- Must have same length first
Validated solution
Reveal Java solution
import java.util.Arrays;
public class Main {
static boolean areAnagrams(String first, String second) {
char[] a = first.toLowerCase().toCharArray();
char[] b = second.toLowerCase().toCharArray();
Arrays.sort(a); Arrays.sort(b);
return Arrays.equals(a, b);
}
public static void main(String[] args) {
System.out.println("Are anagrams: " + areAnagrams("listen", "silent"));
}
}How to approach the problem
Two strings are anagrams when their normalized character multisets match. Sorting both character arrays creates a canonical order that Arrays.equals can compare directly.
Approach
- Define normalization; this version ignores case only.
- Convert to mutable char arrays.
- Sort and compare the full arrays.
Time and space complexity
Time: O(n log n). Space: O(n).
Edge cases to test
- Different lengths can return false before sorting as an optimization.
- Spaces and punctuation count in this version.
Common mistakes
- Comparing the original strings after sorting copies.
- Using == for content equality.
Follow-up challenge
Implement an O(n) frequency-count solution for lowercase a-z input.
Related Strings exercises
- Practice Count Words in Java
- Practice First Non-Repeating Character in Java
- Practice Longest Word in Java
Practice all Strings exercises · Run this idea in the Java compiler