Home » Blog » Anagram Method 1 – HackerRank Solution

Anagram Method 1 – HackerRank Solution

Hello guys,

In this article we are going to solve the anagram problem. I am going to tell you 3 methods to solve the problem.

The set of two string is said to be anagram if they both contains same character with same frequency.

I have tried this problem with following three methods. In this article we are going to see the first method which is using the hashmap.

  1. Using hashmap with counting the frequency
  2. Simple approach with inbuilt method
  3. Simple approach without inbuilt method.

Using hashmap with counting the frequency

In this approach, first we are going to check that if both string is having the same length or not. It is clear that if both strings does not have the same length then it will not be an anagram.

Second, we are creating one method that count the unique character from the string and count frequency of that character. See the below code for countFreq() method. We first create the the object of HashMap<Character,Integer> type, that will store the character as a key and it’s frequency as value. HashMap stores the data in key value pair. Then we will iterate one loop from start middle along with end to middle. We can also use one variable loop, but rather that one variable loop we prefer two variable loop, because it can be helpful to reduce the required time.

Inside the loop we are checking that if the character is present in the HashMap or not. If it presented then we fetch the value for that character and increment that character frequency, and if the character is not presented then we will add that character with 1 frequency. We are going to use two side iteration that will end in middle.

At last we will return the HashMap for the passing string.

static HashMap<Character,Integer> countFreq(String a)
{
        int i,j;
        HashMap<Character,Integer> akey = new HashMap<>();

        for (i=0,j=a.length()-1;i<=j;i++,j--)
        {
            if (akey.containsKey(a.charAt(i)))
            {
                char c = a.charAt(i);
                int newc = akey.get(c) + 1;
                akey.replace(c,newc);
            }
            else
            {
                char c = a.charAt(i);
                akey.put(c,1);
            }
            if (akey.containsKey(a.charAt(j)))
            {
                char c = a.charAt(j);
                int newc = akey.get(c) + 1;
                akey.replace(c,newc);
            }
            else
            {
                char c = a.charAt(j);
                akey.put(c,1);
            }
        }
        return akey;
}

Now look at the method isAnagram() that will check for the strings are anagram or not. First we are checking the length of both string and then calculate the frequency if length of both strings are same using the countFreq() method. Then we iterate first string HashMap that is aFreq with second HashMap that is bFreq and check that if the frequency of the particular character is matching in both strings. It it match then we will return true, otherwise return false.

static boolean isAnagram(String a, String b) 
{
        if (a.length()!=b.length())
            return false;

        int i;
        boolean flag = true;
        HashMap<Character,Integer> aFreq = countFreq(a);
        HashMap<Character,Integer> bFreq = countFreq(b);

        for (Character key : aFreq.keySet())
        {
            if (bFreq.containsKey(key))
            {
                if(aFreq.get(key)!= bFreq.get(key))
                {
                    flag = false;
                    break;
                }
            }
        }

        return flag;
}

The complete code of the problem is below.

import java.util.*;

public class Anagram
{
    static boolean isAnagram(String a, String b) {
        if (a.length()!=b.length())
            return false;

        int i;
        boolean flag = true;
        HashMap<Character,Integer> aFreq = countFreq(a);
        HashMap<Character,Integer> bFreq = countFreq(b);

        for (Character key : aFreq.keySet())
        {
            if (bFreq.containsKey(key))
            {
                if(aFreq.get(key)!= bFreq.get(key))
                {
                    flag = false;
                    break;
                }
            }
        }

        return flag;
    }

    static HashMap<Character,Integer> countFreq(String a)
    {
        int i,j;
        HashMap<Character,Integer> akey = new HashMap<>();

        for (i=0,j=a.length()-1;i<=j;i++,j--)
        {
            if (akey.containsKey(a.charAt(i)))
            {
                char c = a.charAt(i);
                int newc = akey.get(c) + 1;
                akey.replace(c,newc);
            }
            else
            {
                char c = a.charAt(i);
                akey.put(c,1);
            }
            if (akey.containsKey(a.charAt(j)))
            {
                char c = a.charAt(j);
                int newc = akey.get(c) + 1;
                akey.replace(c,newc);
            }
            else
            {
                char c = a.charAt(j);
                akey.put(c,1);
            }
        }
        return akey;
    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String a = scan.next();
        String b = scan.next();
        scan.close();
        boolean ret = isAnagram(a, b);
        System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
    }
}

The above code is not working in HackerRank as in this problem statement HackerRank does not allow to import the libraries or classes. So in next article we are going to see the second approach that is simple approach with inbuilt method without HashMap.

The HackerRank problem can be found at : https://www.hackerrank.com/challenges/java-anagrams

Stay tuned…

Happy Coding

Leave a Reply

Your email address will not be published.