How to Check if Two Strings are Anagrams (Java)

A string is said to be an anagram of another string if they satisfy the following conditions

  • They consist of same letters in their composition
  • The count of each letter is equal in both String

 

General Idea

  • Based on the condition we can find if two strings are an anagram of each other
  • We remove any spaces in the string so the resulting string is just set of characters
  • Then we sort the String
  • Similary we process the other string
  • Compare the two strings, if they are same then the original string is an anagram of other string

 

Java Code
import java.util.*;

class Anagram{
    
      public char[] trimAndSort(String value){
        String copy = value.replaceAll("\\s","").toLowerCase();
        char[] stringChar = copy.toLowerCase().toCharArray();
        Arrays.sort(stringChar);
        return stringChar;
      }
    
      public boolean checkAnagram(String a, String b){
        return Arrays.equals(trimAndSort(a),trimAndSort(b));
      }
    
      public static void main(String args[]){
        Anagram aa  = new Anagram();
        boolean isAnagram =	aa.checkAnagram(" Fermonte", "montefer");
        System.out.print("Strings Fermonte & montefer ? ");
        System.out.println(isAnagram == true ? "Its an anagram" : "Its not anagram");
    
        boolean isThisAnagram =	aa.checkAnagram("A decimal point", "I m a dot in place");
        System.out.print("Strings 'A decimal point' & 'I m a dot in place' ? ");
        System.out.println(isThisAnagram == true ? "Its an anagram" : "Its not anagram");
      }
 }   
Output

Strings Fermonte & montefer ? Its an anagram
Strings 'A decimal point' & 'I m a dot in place' ? Its an anagram

### Complexity Analysis * **Time Complexity**: O(N log N) if using sorting, or O(N) if using a frequency array/hashmap. * **Space Complexity**: O(1) for frequency array (fixed size) or O(N) for hashmap.

Share Your Thoughts

Browse all General articles

Stay Ahead

Only insights that save you time or money. No fluff, ever.

Stay Ahead

Only insights that save you time or money. No fluff.