Java Anagrams Hackerrank Solution

Java Anagrams Hackerrank Solution
Java Anagrams

Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. For this challenge, the test is not case-sensitive. For example, the anagrams of CAT are CATACTtacTCAaTC, and CtA.

Function Description

Complete the isAnagram function in the editor.

isAnagram has the following parameters:

  • string a: the first string
  • string b: the second string


  • boolean: If a and b are case-insensitive anagrams, return true. Otherwise, return false.

Input Format

The first line contains a string .
The second line contains a string .


  • 1<=length(a),length(b)<=50
  • Strings  and  consist of English alphabetic characters.
  • The comparison should NOT be case sensitive.

Sample Input 0


Sample Output 0


Explanation 0

CharacterFrequency: anagramFrequency: margana
A or a33
G or g11
N or n11
M or m11
R or r11

The two strings contain all the same letters in the same frequencies, so we print “Anagrams”.

Sample Input 1


Sample Output 1

Not Anagrams

Explanation 1

CharacterFrequency: anagrammFrequency: marganaa
A or a34
G or g11
N or n11
M or m21
R or r11

The two strings don’t contain the same number of a‘s and m‘s, so we print “Not Anagrams”.

Sample Input 2


Sample Output 2


Explanation 2

CharacterFrequency: HelloFrequency: hello
E or e11
H or h11
L or l22
O or o11

The two strings contain all the same letters in the same frequencies, so we print “Anagrams”.

Code Solution:

//Java Anagrams Hackerrank Solution

import java.util.Scanner;

public class Solution {


    static boolean isAnagram(String a, String b) {
        // Complete the function
        char aa[] = a.toLowerCase().toCharArray();
        char bb[] = b.toLowerCase().toCharArray();
        if(a.length() != b.length()){
            return false;
            return java.util.Arrays.equals(aa, bb);

    public static void main(String[] args) {
        Scanner scan = new Scanner(;
        String a =;
        String b =;
        boolean ret = isAnagram(a, b);
        System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );

//Java Anagrams Hackerrank Solution

Disclaimer: This problem is originally created and published by HackerRank, we only provide solutions to this problem. Hence, doesn’t guarantee the truthfulness of the problem. This is only for information purposes.

Leave a Comment