![]() |
VOOZH | about |
Write a function to check whether two given strings are anagrams 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.
👁 Java-Program-To-Check-Whether-Two-Strings-Are-Anagram
Below is the Program to check if two strings are anagrams Java using Sorting:
The two strings are not anagram of each other
In this method, we first sort both strings and then compare both of them. If both string are equal that means both are Anagram else both strings are not Anagram.
Time Complexity: O(NLogN)
Auxiliary space: O(1).
There are certain methods to write an anagram program in Java as mentioned below:
This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bits and there can be 256 possible characters.
Below is the implementation of the above idea:
The two strings areanagram of each other
Time Complexity: O(n)
Auxiliary space: O(n)
The above implementation can be further to use only one count array instead of two. We can increment the value in the count array for characters in str1 and decrement for characters in str2. Finally, if all count values are 0, then the two strings are anagrams of each other. Thanks to Ace for suggesting this optimization.
Below is the implementation of the above method:
The two strings are anagram of each other
Time Complexity: O(n)
Auxiliary space: O(n)
We can optimize the space complexity of the above method by using HashMap instead of initializing 256 characters array. So in this approach, we will first count the occurrences of each unique character with the help of HashMap for the first string. Then we will reduce the count of each character while we encounter them in the second string. Finally, if the count of each character in the hash map is 0 then it means both strings are anagrams else not.
Below is the code for the above approach:
The two strings are anagram of each other
Time Complexity: O(n)
Auxiliary space: O(n) because using HashMap
Please refer complete article on Check whether two strings are anagram of each other for more details!