Home » Blog » Anagram Method 2 – HackerRank Solution

Anagram Method 2 – 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 second method which is a simple approach with inbuilt methods.

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

Simple approach with inbuilt method

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.

Next step is to convert the string into lowercase as we are performing it as case insensitive manner. Then we will convert the strings into the character array using the toCharArray() method.

Then we are using the inbuilt Arrays class to sort this character array. For this we are using the method Arrays.sort().

Then we will compare both strings array using Arrays class method which is Arrays.equals(), and return the result.

See the below code, Take two string for example S1 = anagram S2 = margana, now let’s sort this character array so the array becomes, S1 = aaagmn S2 = aaagmn, and compare both array gives true.

import java.util.Arrays;
import java.util.Scanner;

public class Anagram2
{
        static boolean isAnagram(String a, String b) 
        {
            if (a.length()!=b.length())
                return false;
    
            char[] aChar = a.toLowerCase().toCharArray();
            char[] bChar = b.toLowerCase().toCharArray();

            Arrays.sort(aChar);
            Arrays.sort(bChar);

            boolean flag = Arrays.equals(aChar,bChar);

            return flag;
        }


    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 also 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 without 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.