Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word formed by rearranging the letters of another word.
Examples
s = 'anagram', t = 'nagaram'
true
Both strings contain the same characters with the same frequencies.
s = 'rat', t = 'car'
false
'r' and 'a' in s do not map to 'c' and 'a' in t.
Constraints
- •
1 <= s.length, t.length <= 5 * 10^4 - •
s and t consist of lowercase English letters.
Approaches
Sort both strings and compare them.
def is_anagram(s, t):
if len(s) != len(t):
return False
return sorted(s) == sorted(t)Use a fixed-size array of 26 to count character frequencies.
def is_anagram(s, t):
if len(s) != len(t):
return False
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
return all(c == 0 for c in count)Use a hash map to count character frequencies in s, then decrement for t.
Diagram
def is_anagram(s, t):
if len(s) != len(t):
return False
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
for char in t:
if char not in count:
return False
count[char] -= 1
if count[char] < 0:
return False
return TrueComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Sorting | O(n log n) | O(n) | Sort both strings and compare them. |
| Character Count Array | O(n) | O(1) | Use a fixed-size array of 26 to count character frequencies. |
| Hash Map | O(n) | O(1) | Use a hash map to count character frequencies in s, then decrement for t. |
Sort both strings and compare them.
Use a fixed-size array of 26 to count character frequencies.
Use a hash map to count character frequencies in s, then decrement for t.
Common Mistakes
Not checking if lengths are equal first
Using count[s[i]]++ without checking if key exists
Forgetting to check that all counts are zero, not just some