🔤 Valid Anagram – Python Solution
Hi All,
Today I solved a simple but important problem: Valid Anagram.
📌 Problem Statement
Given two strings s and t, check whether t is an anagram of s.
👉 An anagram means:
- Both strings contain the same characters
- Same frequency of each character
- Order does not matter
🔍 Examples
Example 1:
s = "anagram"
t = "nagaram"
Output:
True
Example 2:
s = "rat"
t = "car"
Output:
False
💡 Approach
🔹 Method 1: Sorting (Simple)
- Sort both strings
- Compare results
💻 Python Code (Sorting)
def isAnagram(s, t):
return sorted(s) == sorted(t)
🔹 Method 2: Frequency Count (Optimal)
👉 Better approach using dictionary
- Count characters in both strings
- Compare frequencies
💻 Python Code (Dictionary)
def isAnagram(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())
🔍 Dry Run
For:
s = "rat"
t = "tar"
Steps:
- Count s → {'r':1, 'a':1, 't':1}
- Reduce using t → all become 0
Final Output:
True
🖥️ Sample Output
Input: s = "anagram", t = "nagaram"
Output: True
Input: s = "rat", t = "car"
Output: False
⚡ Complexity Analysis
| Method | Time | Space |
|---|---|---|
| Sorting | O(n log n) | O(1) |
| Dictionary | O(n) ✅ | O(1) |
🧠 Why this is important?
- Tests string manipulation
- Introduces frequency counting
- Common in interviews
✅ Conclusion
This problem helped me understand:
- Character frequency counting
- Efficient string comparison
- Optimizing solutions
🚀 A must-know problem for beginners!
Top comments (0)