Given two strings, determine whether they are anagrams.

Any word that exactly reproduces the letters in another order is an anagram. In other words, X and Y are anagrams if by rearranging the letters of X, we can get Y using all the original letters of X exactly once.

 
For example, all these pairs are anagrams as lhs can be rearranged to rhs and vice-versa:

silent = listen
incest = insect

Practice this problem

A simple solution would be to sort given strings. If the strings become equal after sorting, they are anagrams. The time complexity of this solution is O(n.log(n)), where n is the length of the input string.

 
We can also solve this problem in O(n) time. The idea is to maintain the frequency of each character of the first string in a map or a count array. Then for each character of the second string, decrement its frequency and return false if the frequency becomes negative or the character is not present on the map.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Anagram

Java


Download  Run Code

Output:

Anagram

Python


Download  Run Code

Output:

Anagram

The time complexity of the above solution is O(n) assuming constant-time operations for a hash table. The auxiliary space required by the program is O(c), where c is the alphabet size.

Approach 3

Another simple solution is to create two maps and store the frequency of each character of the first and second string in them. Then we can check if both maps are equal or not. If both are found to be equal, then both strings are anagrams.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Anagram

Java


Download  Run Code

Output:

Anagram

Python


Download  Run Code

Output:

Anagram

The time complexity of the above solution is O(n) assuming constant-time operations for a hash table. The auxiliary space required by the program is O(c), where c is the alphabet size.