Java Anagrams HackerRank Solution

Java Anagrams  HackerRank Solution


Java BigDecimal HackerRank Sollution, Java interview questions

Problem
Two strings,  and , are called anagrams if they contain all the same characters in the same frequencies. For example, the anagrams of CAT are CATACTTACTCAATC, and CTA.
Complete the function in the editor. If  and  are case-insensitive anagrams, print "Anagrams"; otherwise, print "Not Anagrams" instead.
Input Format
The first line contains a string denoting .
The second line contains a string denoting .
Constraints
  • Strings  and  consist of English alphabetic characters.
  • The comparison should NOT be case sensitive.
Output Format
Print "Anagrams" if  and  are case-insensitive anagrams of each other; otherwise, print "Not Anagrams" instead.
Sample Input 0
anagram
margana
Sample Output 0
Anagrams
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
anagramm
marganaa
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
Hello
hello
Sample Output 2
Anagrams
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".
Solution
import java.util.Scanner;

public class Solution {

    static boolean isAnagram(String a, String b) {
        // Complete the function
        int arr[]=new int[123];
        boolean isAnagram=true;
       for(char c:a.toCharArray())
int index=(int)c;
  if(65<=index && index<=90)
    index+=32;
  arr[index]++;
    }
for(char c:b.toCharArray())                 // O(n) Time Complexity
{  int index=(int)c;
if(65<=index && index<=90)
    index+=32;
   arr[index]--;
    }
for(int i=0;i<123;i++)
{    if(arr[i]!=0)
    isAnagram=false;
    }
    return isAnagram;
    }
  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" );
    }
}
So, Guys that was the solution of Java Anagrams  HackerRank Solution
 in Java.
If you have any question regarding the post ask me in Comment section.
And also give your solution for the question in the comment, Happy reading.

Post a Comment

0 Comments