Anagram checking in Java

Let’s go over Anagram checking in Java. An anagram is when two strings have the same characters in a different order, e.g., "listen" and "silent".

There are multiple ways to check for anagrams. I’ll cover the most common and efficient methods.


Using Sorting

Idea:

  • Convert strings to char arrays.
  • Sort both arrays.
  • If they are equal, the strings are anagrams.
import java.util.Arrays;

public class AnagramCheck {
    public static boolean isAnagram(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths differ, they can't be anagrams
        if (str1.length() != str2.length()) return false;

        // Convert to char arrays and sort
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);

        return Arrays.equals(arr1, arr2);
    }

    public static void main(String[] args) {
        String str1 = "Listen";
        String str2 = "Silent";

        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

Output:

Listen and Silent are anagrams.

Using Character Count (HashMap or Array)

Idea:

  • Count frequency of each character in both strings.
  • Compare the counts.
public class AnagramCheck {
    public static boolean isAnagram(String str1, String str2) {
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        if (str1.length() != str2.length()) return false;

        int[] count = new int[26]; // For letters a-z

        for (int i = 0; i < str1.length(); i++) {
            count[str1.charAt(i) - 'a']++;
            count[str2.charAt(i) - 'a']--;
        }

        for (int c : count) {
            if (c != 0) return false;
        }

        return true;
    }

    public static void main(String[] args) {
        String str1 = "Triangle";
        String str2 = "Integral";

        if (isAnagram(str1, str2))
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        else
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
    }
}

Output:

Triangle and Integral are anagrams.

Notes:

  • Sorting method: Simple, O(n log n) due to sorting.
  • Character count method: More efficient, O(n) time and O(1) space (for lowercase letters).
  • Can be extended to Unicode by using a HashMap instead of an array.

Leave a Reply