The Valid Anagram problem is a fundamental string problem that checks whether two strings contain the same characters in a different order.
π Problem Statement
Given two strings s and t, return true if t is an anagram of s, otherwise return false.
π An anagram means both strings have:
- Same characters
- Same frequency of each character
π Examples
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
π§ Intuition
To check if two strings are anagrams:
- Both strings must have the same length
- The frequency of each character must match
π Approach 1 (Sorting Method β Simple)
Step-by-Step:
- Sort both strings
- Compare them
π» Python Code
```python id="a1"
def is_anagram(s, t):
return sorted(s) == sorted(t)
print(is_anagram("anagram", "nagaram"))
---
β‘ Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
---
π Approach 2 (Frequency Count β Optimal)
Step-by-Step:
1. If lengths are different β return False
2. Count frequency of each character
3. Compare both counts
---
π» Python Code
```python id="a2"
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
return all(value == 0 for value in count.values())
print(is_anagram("anagram", "nagaram"))
β‘ Complexity
Time Complexity: O(n)
Space Complexity: O(1) (only 26 lowercase letters)
π₯ Why This Works
- Tracks exact frequency of each character
- Ensures both strings match perfectly
- Faster than sorting approach
β οΈ Follow-Up (Unicode Characters)
If strings contain Unicode characters:
π Use a dictionary (already done above)
π Avoid fixed-size arrays (since characters are not limited)
π Conclusion
Valid Anagram is a simple yet important problem that teaches:
- String manipulation
- Hashing (frequency counting)
- Optimization techniques
Top comments (0)