VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-check-strings-anagram-using-hashmap/

⇱ Java Program to Check Strings Anagram Using HashMap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Check Strings Anagram Using HashMap

Last Updated : 30 Dec, 2023

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:


Output
The two strings are not anagram of each other

Complexity of the above method

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

Comment