Open In App

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

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different.

For example, “abcd” and “dabc” are an Anagram of each other.

check-whether-two-strings-are-anagram-of-each-other

Approach: Hashmaps can be used to determine if two given strings are anagrams or not. The approach involves mapping the characters of each string to a hashmap, where the characters serve as keys and their frequencies as values. Then, the hashmaps for both strings are compared to check if they contain the same set of characters with the same frequencies. If the HashMaps are equal, the strings are considered anagrams; otherwise, they are not.

Implementation: 

Java
// Java code to check whether two strings 
// are Anagram or not using HashMap 

import java.util.HashMap;

class GFG {
    // Function to check whether two strings
    // are an anagram of each other
    static boolean areAnagram(String str1, String str2) {

        HashMap<Character, Integer> hmap1
                = new HashMap<Character, Integer>();

        char arr1[] = str1.toCharArray();

        // Mapping first string
        for (char c : arr1) {
            hmap1.put(c, hmap1.getOrDefault(c, 0) + 1);
        }

        // Removing characters of second string from hashmap
        for (char c : str2.toCharArray()) {
            if (!hmap1.containsKey(c)) {
                return false; // If a character is not found in the hashmap, it's not an anagram
            }
            int count = hmap1.get(c);
            if (count == 1) {
                hmap1.remove(c); // Remove character if count is 1
            } else {
                hmap1.put(c, count - 1); // Decrement count otherwise
            }
        }

        // If hashmap is empty, strings are anagrams
        return hmap1.isEmpty();
    }

    // Test function
    public static void test(String str1, String str2) {

        System.out.println("Strings to be checked are:\n"
                + str1 + "\n" + str2 + "\n");

        // Find the result
        if (areAnagram(str1, str2))
            System.out.println("The two strings are "
                    + "anagrams of each other\n");
        else
            System.out.println("The two strings are not"
                    + " anagrams of each other\n");
    }

    // Driver program
    public static void main(String args[]) {

        // Get the Strings
        String str1 = "geeksforgeeks";
        String str2 = "forgeeksgeeks";

        // Test the Strings
        test(str1, str2);

        // Get the Strings
        str1 = "geeksforgeeks";
        str2 = "geeks";

        // Test the Strings
        test(str1, str2);
    }
}

Output
Strings to be checked are:
geeksforgeeks
forgeeksgeeks

The two strings are anagrams of each other

Strings to be checked are:
geeksforgeeks
geeks

The two strings are not anagram of each other

Complexity of the above Method:

Time Complexity: O(l1 + l2) where l1 and l2 are lengths of strings.
Auxiliary space: O(m1) where is the number of unique characters in str1.

Please suggest if someone has a better solution which is more efficient in terms of space and time.

Related Article: Check whether two strings are anagram of each other



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads