π€ 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)