Valid Anagram
Problem
Given two strings s and t, check if t is an anagram of s.
An anagram means both strings contain the same characters with the same frequency, just arranged differently.
Strategy
The idea is simple:
- Count how many times each character appears in
s - Then try to “cancel out” those counts using
t
If everything balances to zero, the strings are anagrams.
Code
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
Key Lines Explained
if len(s) != len(t):
If lengths differ, they can’t be anagrams.count[ch] = count.get(ch, 0) + 1
Count frequency of each character ins.if ch not in count or count[ch] == 0:
If a character intdoesn’t match, returnFalse.count[ch] -= 1
Reduce count as we match characters.
Why This Works
Anagrams have the same characters in the same quantities.
By counting and cancelling, we’re checking if both strings are perfectly balanced.
Complexity
- Time: O(n)
- Space: O(1) (since only lowercase letters)
Final Note
This problem is less about strings and more about counting.
Once you think in terms of frequency instead of order, it becomes straightforward.
Top comments (0)