Open In App

Java Program to Check Strings Anagram Using HashMap

Last Updated : 30 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Java Program to check whether two given strings are anagrams of each other or not using HashMap.

What is an Anagram?

A string is an anagram of another string if it contains the same characters in the same or in different order.

Example of Anagram in Java

Input: s1 = “abcd”
s2 = “cadb”

Output: Two Strings are Anagram of each other

Hashmap to Check Anagrams in Java

This method is similar to the frequency array method but this method is optmized since we are not using all the 256 characters, in this method first we iterate in the first string and store the frequency of each character of the first string in the hashmap, then we iterate in the second string and check if the charcter is present in the hashmap or not if it is not present then return a false else reduce the frequency of the character in hashmap by 1 and at last check all the values in the hashmap are zero or not if everything is zero then both strings are anagram else they are not anagrams.

Program to Check Anagram using HashMap:

Java




// Java Program to Check if
// String are Anagram using
// HashMap
import java.io.*;
import java.util.*;
  
// Driver Class
class GFG {
    // main function
    public static boolean is_Anagram(String a, String b)
    {
        // Length of String Equal or not
        if (a.length() != b.length()) {
            return false;
        }
  
        // Create a HashMap
        HashMap<Character, Integer> map = new HashMap<>();
  
        // Using Loop to iterate String
        for (int i = 0; i < a.length(); i++) {
  
            if (map.containsKey(a.charAt(i))) {
                // If contains increase count by 1 for that
                // character
                map.put(a.charAt(i),
                        map.get(a.charAt(i)) + 1);
            }
            else {
                // first occurence of the element
                map.put(a.charAt(i), 1);
            }
        }
  
        // Now loop over String b
        for (int i = 0; i < b.length(); i++) {
  
            // Checking current character already
            // exists in HashMap
            if (map.containsKey(b.charAt(i))) {
                // Maintaing the count in map
                map.put(b.charAt(i),
                        map.get(b.charAt(i)) - 1);
            }
            else {
                return false;
            }
        }
  
        // Extract all keys of HashMap/map
        Set<Character> keys = map.keySet();
  
        // Checking if count of all the elements
        // are equal
        for (Character key : keys) {
            if (map.get(key) != 0) {
                return false;
            }
        }
        // Returning True as all keys are zero
        return true;
    }
    public static void main(String[] args)
    {
        String str1 = "gram";
        String str2 = "arm";
  
        // Function call
        if (is_Anagram(str1, str2))
            System.out.print("The two strings are "
                             + "anagram of each other");
        else
            System.out.print("The two strings are "
                             + "not anagram of each other");
    }
}


Output

The two strings are not anagram of each other

Complexity of the above method

Time Complexity: O(N)
Space Complexity: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads