Detect whether a string is anagram of the another string. The normal brute force way would be like this,
- The above approach ignores all space character ‘ ‘ and checks for occurrence of a character in the anagram string. If the number of equal characters is equal to the number of characters in source string, then the string is an anagram!!..
- iter is the iterator for the anagram string
- We iterate until we find a matching character in the iter. If we find one, we just increment the count and break.
- iana will be equal to isrc only when characters in source string = anagram string. This is the invariant we need to use to prove the correctness of the above code
- sort both the strings and check whether both are equal!!
- Take count of characters in original string first and then start decrementing the count when seeing the same in the anagram string. If the count becomes zero for all the recorded character entries, then the string is an anagram. This approach is little bit faster than our above O(N2) approach.