Valid Anagram | String Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given two strings S and T, find out if T is an anagram of S.

Example 

Valid Anagram

Input :- S = "anagram" T = "nagaram"
Output :- true
Input :- S = "sun" T = "car"
Output :- false

Solution

This problem can be solved in following steps :-

  1. Create the character array from both the input String S and T.
  2. Create an integer array (count array) of size 26 (Total number of characters in the English language), This array will be used to store the frequency of each character in the input string.
  3. Traverse the character array S from start (index 0) to end (n-1, where n is the length of an array) and convert each character into an index of count array by subtracting the character from ‘a’ and converting it into ASCII code. Increase the count for the calculated index by 1.
  4. Traverse the character array T from start (index 0) to end (n-1, where n is the length of an array) and convert each character into an index of count array by subtracting the character from ‘a’ and converting it into ASCII code. Decrease the count for the calculated index by 1.
  5. Traverse the count array from start (index 0) to end (n-1, where n is the length of an array) and check if any value is not equal to zero. If yes then return false else return true.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		boolean result = main.isAnagram("anagram", "nagaram");
		System.out.print(result);
	}
	
	/* Solution */
	public boolean isAnagram(String s, String t) {
        
        int[] countArray = new int[26];
        char[] sArray = s.toCharArray();
        char[] tArray = t.toCharArray();
        
        for(int i=0; i<sArray.length; i++){
            countArray[sArray[i]-'a']++;
        }
        
        for(int i=0; i<tArray.length; i++){
            countArray[tArray[i]-'a']--;
        }
        
        for(int i=0; i<countArray.length; i++){
            if(countArray[i] != 0){
                return false;
            }
        }
        return true;
    }
}

Result

true

Similar Post

  1. Group Anagrams
  2. Find All Anagrams in a String
  3. First Unique Character in a String

That’s all for Valid Anagram in Java, If you liked it, please share your thoughts in a comments section and share it with others too.