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

  1. Sort both strings and compare
  2. Or count character frequencies
  3. 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

  1. Define normalization; this version ignores case only.
  2. Convert to mutable char arrays.
  3. 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 all Strings exercises · Run this idea in the Java compiler