Anagram Program in Java

0

It is one of the most asked interview question from the string data structure . Write a program to find whether the two strings are Anagram or not .



Anagram :

Two strings are said Anagram if both of them have same letters for the same number of frequency .

String str1 = "coding" ; 
String str2 = "ingcod";

Then str1 and str2 are the anagrams to each other .

In this article we are going to see how can we find out two strings are anagram or not .

Code :



public class StringE 
{
   
    public static boolean anagram(String str1String str2)
    {
        //creating an array of length 26
        int []arrnew int[26];

        //creating frequency array
        for(int i=0;i<str1.length();i++)
        {
            //incrementing the values for first string
            arr[str1.charAt(i)-'a']++;        
        }

        //doing opposite with the frequency array
        for(int i=0;i<str2.length();i++)
        {
            arr[str2.charAt(i)-'a']--;
        }

        //if there exist non zero values then not anagram
        for(int i=0;i<26;i++)
        {
            if(arr[i]!=0)
                return false;
        }

        //will return true if all values are zero
        return true;   

    }

    public static void main(String[] args)
    {
        String str1"qwekakh";
        String str2"hsfajja";
        
        System.out.println(anagram(str1str2));
        System.out.println(anagram("hi", "ih"));

    }

}

Output

    false
    true


Logic :

1. First of all we will create a frequency array for the letters in string first .

String str = "hindi";

Then the array will have the frequency of each letter. Array will look like this.

arr = { 0,0,0,1,0,0,0,1,2,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}

2. After creating this frequency array we will do the same but opposite with the second string for every letter we will decrement the value of array by one . 

String str2 = "indih";

Then for every letter in string we will decrement the array value . Array will look like this.

arr = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}

So now as you can see our array contains all zero that means these two strings are anagram . If array contains any non zero value then these strings are not anagrams . 

Time Complexity : O(m+n) : since we are running two loops there one with the length m and the other with the length n

Space Complexity : O(1) : we are using an array of length 26 , so it is nothing but O(1).









Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !