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);
    }
}