My Thinking and Approach
Introduction
In this problem, I was given two strings and asked to check whether one string is an anagram of the other.
An anagram means both strings contain the same characters with the same frequency but possibly in a different order.
Problem Statement
Given two strings
sandtReturn true if
tis an anagram ofsOtherwise return false
-
Conditions:
- Strings contain only lowercase English letters
My Initial Thought
At first, I considered:
- Sorting both strings
- Comparing them
If both sorted strings are equal, then they are anagrams.
Key Observation
Instead of sorting:
- I can count frequency of each character
- Compare frequencies of both strings
Optimized Approach
I decided to:
- Use a dictionary to count characters
- Compare counts
Logic:
- If lengths are not equal → return false
- Count characters of first string
- Decrease count using second string
- If all counts become zero → valid anagram
My Approach (Step-by-Step)
- If length of s and t are not equal → return false
- Create a dictionary count
- Traverse string s:
-
Increase count of each character
- Traverse string t:
Decrease count of each character
-
If any count becomes negative → return false
- If all counts are zero → return true
Code (Python)
Below is the implementation clearly separated inside a code block:
```python id="t3q4xz"
class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if ch not in count or count[ch] == 0:
return False
count[ch] -= 1
return True
---
## Example Walkthrough
### Input:
```text id="h8u9dn"
s = "anagram", t = "nagaram"
Steps:
- Count characters in s
- Reduce counts using t
- All counts become zero
Output:
```text id="9pkz0y"
true
---
## Complexity Analysis
| Type | Complexity |
| ---------------- | ---------- |
| Time Complexity | O(n) |
| Space Complexity | O(1) |
---
## Key Takeaways
* Sorting is simple but not optimal
* Frequency counting is efficient
* Hashmap helps in tracking characters
---
## Conclusion
This problem helped me understand how to efficiently check anagrams using character frequency instead of sorting.
---
Top comments (0)