#242
Valid Anagram
EasyHash TableStringSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of sorting, we can count the frequency of each character in both strings using a hash map. If the counts match, the strings are anagrams.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map for characters in string s.
- 2Step 2: Decrease the count for each character found in string t.
- 3Step 3: Check if all counts in the frequency map are zero.
solution.py4 lines
1from collections import Counter
2
3def isAnagram(s, t):
4 return Counter(s) == Counter(t)ℹ
Complexity note: Counting characters takes O(n) time, and we use a hash map to store counts, which takes O(n) space in the worst case.
- 1Anagrams must have the same characters with the same frequency.
- 2Sorting is a straightforward approach but not the most efficient.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.