- Leetcode Learning System
- Posts
- Day 7 - Valid Anagram
Day 7 - Valid Anagram
🧩 Problem:
Given two strings s
and t
, return True
if t
is an anagram of s
, and False
otherwise.
🧪 Examples:
Example 1
Input: s = "anagram"
, t = "nagaram"
Output: True
Example 2
Input: s = "rat"
, t = "car"
Output: False
📏 Constraints:
1 <= s.length, t.length <= 5 * 10^4
s
andt
consist of lowercase English letters
🧠 How to Approach It
An anagram means both strings contain the same characters, just in a different order. The key insight is:
Same characters
Same frequencies
There are several ways to solve this:
✅ Hash maps / dictionaries to count character frequency
🧵 Or sort both strings and compare (less efficient for large inputs)
Here we use two dictionaries and compare their contents.
Bonus: To support Unicode, use Python’s collections.Counter
which handles character counting out-of-the-box and works with all characters.
✅ Python Solution:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_count = {}
t_count = {}
for i in s:
s_count[i] = s_count.get(i, 0) + 1
for i in t:
t_count[i] = t_count.get(i, 0) + 1
return s_count == t_count
💡 Optional Unicode support:
from collections import Counter
def isAnagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)
🧵 TL;DR:
Count characters using dictionaries or
Counter
Equal counts = valid anagram
Works in
O(n)
time