Anagrams HackerRank Solution

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. This Java program takes two strings as input and checks if they are anagrams of each other.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Anagrams HackerRank Solution HackerRank solution using CodeRankGPT:

The solution approach is to first check if the lengths of the two strings are equal. If they are not, the function immediately returns false. If they are, the function converts both strings to lowercase and iterates through each character in the first string. For each character, it checks if it exists in the second string. If it does, it removes the first occurrence of that character from the second string. If it doesn't, it returns false. After iterating through all characters, if the second string is empty, it means all characters from the first string were found and removed from the second string, hence they are anagrams, and the function returns true.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.strings;

import java.util.Scanner;

/**
 *
 */
public class JavaAnagrams {

	static boolean isAnagram(String a, String b) {
		if (a.length() != b.length()) {
			return false;
		} else {
			for (int i = 0; i < a.length(); i++) {
				char ch = a.toLowerCase().charAt(i);
				b = b.toLowerCase();
				if (b.indexOf(ch) != -1) {
					b = b.replaceFirst(ch + "", "");
				} else {
					return false;
				}
			}
			return b.length() == 0;
		}
	}

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

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform