Check whether two Strings are Anagram of each other using HashMap in Java


Anagram Strings are those strings that have the same characters in each of the strings only the order in which they are arranged changes. In other words, a string is an anagram string if it forms a meaningful word after rearranging the characters of the other string. Some examples of anagram strings are “cat and act”, “care and race”. Both of them have the same characters and their frequencies.

In this article, we will be discussing the approach to check whether the two strings are anagrams of each other or not using the HashMaps in Java.

Problem Statement

Given two strings, we need to check whether both the strings are anagram of each other or not using a hashmap in Java. Let us take an example to understand it better.

Input: str1: care
  str2: race
Output: True 

Algorithm for checking the anagrams string using Hashmap

  • Step 1 − If the lengths of both the strings are not equal, immediately return false.

  • Step 2 − Declare two HashMaps.

  • Step 3 − Iterate over the elements of the first string and store their frequency into the first hashmap.

  • Step 4 − Now, iterate over the second string and store their frequency into the second hashmap.

  • Step 5 − Now, check if both the hashmaps are equal or not.

  • Step 6 − If yes, return true.

  • Step 7 − Otherwise, return false.

Now, let us discuss some approaches for the checking the anagram strings.

Approaches

  • Approach 1 − The approach is using two hashmaps and storing the frequency counts of both the strings in the different hashmaps. If the both the hashmaps are equal then both the strings are anagrams of each other.

  • Approach 2 − In the second approach, there is only one hashmap. First of all, the frequency count of the first string is stored in the hashmap and then the frequency is decremented if the same character occurs in the second string. At the end, if the all the values of the hashmap are zero, then the two strings are anagram of each other, otherwise not.

Approach 1

In this approach, we will be discussing the program code to check whether the two given strings are anagrams of each other or not using two HashMaps in Java. The first hashmap stores the frequencies of the characters of the first string and the second stores the frequencies of the second string. After which, we check if both the hashmaps are equal, then the strings are anagram otherwise not.

Below is the program code for the same.

Program Code

import java.util.*;
public class Main 
{
	public static boolean checkAnagram(String s1, String s2)
	{
		if (s1.length() !=s2.length()) {
			return false;
		}
		
		//Declaration of the HashMaps
		HashMap<Character, Integer> mp1 = new HashMap<>();
	    	HashMap<Character, Integer> mp2 = new HashMap<>();
		for (int i = 0; i < s1.length(); i++) {
			if (mp1.containsKey(s1.charAt(i))) { 
				mp1.put(s1.charAt(i), mp1.get(s1.charAt(i)) + 1);
			}
			else {
				mp1.put(s1.charAt(i), 1);
			}
		}
		
		for (int i = 0; i < s2.length(); i++) {
			
			if (mp2.containsKey(s2.charAt(i))) {
				mp2.put(s2.charAt(i), mp2.get(s2.charAt(i)) + 1);
			}
			else {
				mp2.put(s2.charAt(i), 1);
			}
		}
	
		//Checking if the hashmaps are equal or not
		if(mp1.equals(mp2)){
		   return true;
		}
		else{
		   return false;
		}
	}
	public static void main(String[] args)
	{
		String a = "acra";
		String b = "cary";
		if (checkAnagram(a, b))
			System.out.print("True");
		else
			System.out.print("False");
   }
}

Output

False

The complexity for the above approach is as follows −

Time Complexity − O(N)

Space Complexity − O(2N)

Approach 2

Using two hashmaps increases the complexity of the previous approach, therefore, now we will be discussing another one in which we are just using a single hashmap and finding if the strings are anagrams of each othere or not.

In this approach, we will be discussing the program code to check whether the two given strings are anagrams of each other or not using only one HashMap in Java. The hashmap first stores the frequencies of the characters of the first string and then decrements these frequencies for the second string. If the hashmap values then turns to be 0 then the strings anagram strings.

Below is the program code for the same.

Program Code

import java.util.*;
public class Main 
{
	public static boolean checkAnagram(String s1, String s2)
	{
		if (s1.length() != s2.length()) {
			return false;
		}
		
		//Declaration of the HashMap
		HashMap<Character, Integer> mp = new HashMap<>();
	
		for (int i = 0; i < s1.length(); i++) {
			if (mp.containsKey(s1.charAt(i))) { 
				mp.put(s1.charAt(i), mp.get(s1.charAt(i)) + 1);
			}
			else {
				mp.put(s1.charAt(i), 1);
			}
		}
		for (int i = 0; i < s2.length(); i++) {
			if (mp.containsKey(s2.charAt(i))) { 
				mp.put(s2.charAt(i), mp.get(s2.charAt(i)) - 1);
			}
			else {
				return false;
			}
		}
		for (Character key : mp.keySet()) {
			if (mp.get(key) != 0) {
				return false;
			}
		}
		
		return true;
	}
	public static void main(String[] args)
	{
		String a = "care";
		String b = "race";

		if (checkAnagram(a, b))
			System.out.print("True");
		else
			System.out.print("False");
	}
}

Output

True

The complexity for the above approach is as follows −

Time Complexity − O(N)

Space Complexity − O(N)

Conclusion

In this article, we have discussed two techniques for checking whether the two strings are anagrams of each other or not using HashMap in Java. The first method uses two hashmaps are storing the frequencies of the characters whereas the second method uses only hashmap for solving the problem statement.

Updated on: 18-Jul-2023

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements