![]() |
VOOZH | about |
Java Program to check whether two given strings are anagrams of each other or not using HashMap.
A string is an anagram of another string if it contains the same characters in the same or in different order.
Input: s1 = "abcd"
s2 = "cadb"
Output: Two Strings are Anagram of each other
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.
The two strings are not anagram of each other
Time Complexity: O(N)
Space Complexity: O(1)