Check whether two strings are anagrams of each other using unordered_map in C++
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.
Approach: Unordered Map can also be used to find if any two given strings are anagrams or not. The idea is to store each character of the first string in the map, with its frequency as value, and after that check for each character of the second string in the map, and if the character is found in the map, reduce its frequency value from the map. If the frequency of a character becomes 0, erase it from the map and at last if the map becomes empty, that means all the characters of the first string are there in the second string with the same number of occurrences(frequency of each character). Implementation:
Strings to be checked: geeksforgeeks forgeeksgeeks The two strings areanagram of each other Strings to be checked: geeksforgeeks geeks The two strings are not anagram of each other
Time Complexity: O(l1 + l2) where l1 and l2 are lengths of strings.
Auxiliary space: O(m1 + m2) where m1 and m2 are numbers of unique characters in each string.
Please suggest if someone has a better solution which is more efficient in terms of space and time.
This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Check whether two strings are anagram of each other
- Check whether two Strings are Anagram of each other using HashMap in Java