- Link: 242. Valid Anagram - Easy
- Track: NeetCode150
Question
Restate the problem
Anagram: same character, same frequency, different order
- Given two strings
sandt - Return
trueiftis an anagram ofs, returnfalseif not anagram.
Edge Case
s = [aaa], t = [aa]→ False, different frequencys = [], t = []→ True
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Hashmap | O(n) | O(k) |
| Method 2 | Sort | O() | O(n) |
Method 1 - Hashmap
Approach
- Compare the
slength andtlength, if not, return False - Counter
s,count = {char: frequency} - For each character
cint- If
cnot incountor count is 0, returnFalse - Decrement count
- If
- return
True
Complexity
- Time Complexity: O(n)
- Space Complexity: O(k)
- k = number of distinct characters in s
Code
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
counter = Counter(s)
for char in t:
if counter[char] < 1:
return False
counter[char] -= 1
return TrueMethod 2 - Sort
Complexity
- Time Complexity: O()
- Space Complexity: O(n)
Code
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)Mistake:
list.sort()works in-place, strings are immutable, cannot use.sort().
History
- Feb-27-2026 Solved