What is Anagram Check?
An Anagram Check determines whether two strings contain exactly the same characters with the same frequencies, regardless of their order. For example, "listen" and "silent" are anagrams because they contain the same letters.
Example
- First String: "listen"
- Second String: "silent"
- Sort both strings
- "eilnst" == "eilnst"
- Therefore, both strings are anagrams.
There are multiple approaches to solve this problem. A common method is to sort both strings and compare them. Another efficient approach is to count the frequency of each character using a HashMap and compare the frequency maps.
Algorithm Steps
- Check if both strings have the same length.
- Convert both strings to lowercase (optional).
- Sort both strings alphabetically.
- Compare the sorted strings.
- If both are identical, return True; otherwise return False.
Time Complexity
- Best Case: O(n log n) using sorting.
- Using HashMap Frequency Count: O(n) time and O(n) auxiliary space.
Time Complexity Analysis
Anagram checking is widely used in text processing, spell checkers, cryptography, word games, and coding interviews.