Instagram
youtube
Facebook
Twitter

Anagram Strings program with Java HackerRank Solutions

Objective

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

Returns

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

Input Format

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

Constraints

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

Sample Input 1

anagram
margana

Sample Output 1

Anagrams

Sample Input 2

anagramm
marganaa

Sample Output 2

Not Anagrams

Solution

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

public class Anagram {

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

        a = a.toLowerCase();
        b = b.toLowerCase();

        char[] Arr1 = a.toCharArray();
        char[] Arr2 = b.toCharArray();
        Arrays.sort(Arr1);
        Arrays.sort(Arr2);

        return Arrays.equals(Arr1, Arr2);
    }

    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");
    }
}

Steps involved in the solution

1. Import the necessary packages (java.util.Arrays and java.util.Scanner) for array operations and input reading.

2. Create a public class named Anagram to encapsulate the program.

3. Declare a static method named isAnagram that takes two strings, a and b, as parameters and returns a boolean indicating whether they are anagrams.

4. Within the isAnagram method, check if the lengths of the input strings a and b are equal. Convert the strings to lowercase, convert them to char arrays, sort the arrays, and then compare them.

5. In the main method, create a Scanner object to read input from the standard input. Prompt the user to enter two strings (a and b).

6. Call the isAnagram method with the input strings a and b, and store the result in a boolean variable ret.

7. Print "Anagrams" if ret is" true, and "Not Anagrams" if ret is false.