Learnitweb

Java program to check if two strings are anagram

1. Problem

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once.

For example:

  • ‘Listen’ can be rearranged to form ‘Silent’.
  • ‘restful’ can be rearranged to form ‘fluster’.

2. Steps to check if two strings are anagram

  1. Check if the lengths are the same.
  2. Normalize the strings (Optional but useful if case sensitivity and spaces don’t matter):
    – Convert both strings to lowercase (or uppercase).
    – Remove spaces or special characters if necessary.
  3. Sort the letters of both strings alphabetically.
  4. If the sorted versions of the strings are identical, they are anagrams.

3. Program

import java.util.Arrays;

public class AnagramProblem {

    public boolean solve(char[] s1, char[] s2) {

        if(s1.length != s2.length) return false;

        // sort the letters of the strings
        Arrays.sort(s1);
        Arrays.sort(s2);

        // compare letters one by one
        // Overall running time is O(NlogN) + O(N) = O(NlogN)
        for(int i=0;i<s1.length;++i)
            if(s1[i] != s2[i])
                return false;

        return true;
    }

    public static void main(String[] args){
        String str1 = "silent";
        String str2 = "listen";
        AnagramProblem anagramProblem = new AnagramProblem();
        boolean result = anagramProblem.solve(str1.toCharArray(), str2.toCharArray());
        System.out.println(result);
    }
}

Java 8 Anagram Check using Streams

import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AnagramCheck {
    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        boolean isAnagram = areAnagrams(str1, str2);
        System.out.println("Are Anagrams? " + isAnagram);
    }

    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false; // If lengths are different, they can't be anagrams
        }

        return Arrays.stream(str1.split(""))
                .sorted()
                .collect(Collectors.joining())
                .equals(
                        Arrays.stream(str2.split(""))
                                .sorted()
                                .collect(Collectors.joining())
                );
    }
}

Output:

Are Anagrams? true

Explanation:

  • Check length: If lengths are different, return false.
  • Convert String to Stream:
    • str1.split("") → Converts the string into an array of characters.
    • Arrays.stream(str1.split("")) → Creates a stream from the array.
  • Sort characters: sorted()
  • Join back to string: collect(Collectors.joining())
  • Compare sorted versions of both strings.

Alternative Approach: Using Character Frequency Map

You can also check anagrams by counting character occurrences using Collectors.groupingBy().

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AnagramUsingMap {
    public static void main(String[] args) {
        String str1 = "triangle";
        String str2 = "integral";

        boolean isAnagram = getFrequencyMap(str1).equals(getFrequencyMap(str2));
        System.out.println("Are Anagrams? " + isAnagram);
    }

    public static Map<Character, Long> getFrequencyMap(String str) {
        return str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}