Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
We strongly recommend that you click here and practice it, before moving on to the solution.
Method 1 (Use Sorting)
1) Sort both strings
2) Compare the sorted strings
The two strings are not anagram of each other
Time Complexity: Time complexity of this method depends upon the sorting technique used. In the above implementation, quickSort is used which may be O(n^2) in worst case. If we use a O(nLogn) sorting algorithm like merge sort, then the complexity becomes O(nLogn)
Method 2 (Count characters)
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 bit and there can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.
The two strings are anagram of each other
The above implementation can be further to use only one count array instead of two. We can increment the value in count array for characters in str1 and decrement for characters in str2. Finally, if all count values are 0, then the two strings are anagram of each other. Thanks to Ace for suggesting this optimization.
If the possible set of characters contains only English alphabets, then we can reduce the size of arrays to 52 and use str[i] – ‘A’ as an index for count arrays. This will further optimize this method.
Time Complexity: O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Python sorted() to check if two strings are anagram or not
- Longest common anagram subsequence from N strings
- Remove minimum number of characters so that two strings become anagram
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
- Using Counter() in Python to find minimum character removal to make two strings anagram
- PHP program to check for Anagram
- Check if any anagram of a string is palindrome or not
- Check if binary representations of two numbers are anagram
- Check if binary representation of a given number and its complement are anagram
- Python Dictionary | Check if binary representations of two numbers are anagram
- Meta Strings (Check if two strings can become same after a swap in one string)
- Check if two strings are permutation of each other
- Check if two strings are k-anagrams or not
- Check whether Strings are k distance apart or not
- Check if two given strings are isomorphic to each other