There are many classic problems in programming and this is one of them. It is not much difficult to solve. In this article, you will come to know about anagram and how to find out that a string is an anagram or not. However, before moving on to the solution directly please try to solve it yourself.
An anagram refers to a word or phrase made by reorganizing the letters of another word or phrase. If a string is an anagram of another then it simply means that the word is the reorganization of first. For example listen and silent, heart and earth. To avoid complexity, we can consider that the strings have the same length and prepared from the group of 26 lowercase alphabetic characters and symbols.
Our goal is to create programs using sort and compare method, and count and compare method that can help in detecting if a string is an anagram or not. Count and compare method involves some complexity while sort and compare method is a time-efficient one.
If two strings that are different from each other then they will be considered as anagram only if both contain the same characters. The solution involves receiving a string from the user and storing them in different variables. After that, the strings will be sorted using sorted() and compared to get the end result. If we will start to sort strings alphabetically, we will get the same string if they are anagrams.
In the above code, you will find that this algorithm looks like O(n) because there is only one iteration for comparing the n characters after sorting. You will find that this algorithm and sorting process will have the same order of magnitude.
It is much easier than the above method. It considers the fact that any two anagrams have the exact number of a’s, exact number of b’s, exact number of c’s, and many others. To find out that two strings are an anagram or not, count the number of times each character is present. Every time you will observe a particular character, the counter will be stepped up to that position. If in the last, the two lists of the counter have no difference then the strings are anagram.
In this code, there are several iterations in the solution. The two iterations from the start help in counting characters depending on n. The next iteration, which is the third one, compares two lists of counts. Adding all the possible 26 steps provides T(n)=2n+26T(n), meaning O(n). This is how you will get a linear order of magnitude algorithm.