Check if Two Strings Are Anagrams of Each Other
- Shreyas Naphad
- Jun 17, 2024
- 1 min read
In this article, we will solve the problem of checking if two given strings are anagrams of each other.
Two strings are anagrams if they contain the same characters with the same frequencies but in different orders.
Example
Input: s1 = "listen", s2 = "silent"
Output: true
Explanation: Both strings contain the same characters with the same frequencies.
Solution:
To solve this problem, we can use the following approach:
1. Check Lengths:
o If the lengths of the two strings are different, they cannot be anagrams.
2. Count Character Frequencies:
o Use a hash map to count the frequency of each character in both strings.
3. Compare Frequencies:
o Compare the frequency counts of both strings. If they match for all characters, the strings are anagrams.
Time Complexity: O(N)
Space Complexity: O(1)
Comments