Valid Anagram
Problem
Given two strings
An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Constraint:
s and t, return true if t is an anagram of s, and false otherwise.An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Constraint:
s and t consist of lowercase English letters only.
Examples
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Example 3
Input: s = "a", t = "a"
Output: true
Key Insight
You don't care about order. You care about frequency.
Anagram = same character frequencies. Count and compare.
How to Approach This Problem
Pattern Recognition: When you see keywords like
valid anagram arrays-and-hashing,
think Hash Set / Hash Map.
Step-by-Step Reasoning
1
If two strings are anagrams, what must be true about their lengths?
Answer: Lengths must be equal
Anagrams use all original letters exactly once. If lengths differ, one string has letters the other doesn't. This is a quick O(1) early exit check.
2
Two strings are anagrams if they have the same ___ for each character.
Answer: Frequency/count
Order (position) doesn't matter - that's the whole point of anagrams. We only care that each letter appears the same number of times in both strings.
3
Which approach correctly checks if two strings are anagrams?
Answer: Count character frequencies and compare
We need to verify identical character counts. Direct equality check would fail (different order). Substring check is wrong concept entirely.
4
What's the best way to store character frequencies?
Answer: An array of size 26 (for a-z)
Since we only have lowercase letters (a-z), a fixed-size array of 26 integers is perfect. Index 0 = 'a' count, index 1 = 'b' count, etc. Hash map also works but array is simpler and faster for fixed alphabet.
5
Which algorithm correctly determines if s and t are anagrams?
Answer: Both A and B work
Both approaches work! Sorting: O(n log n) time, O(1) space if in-place. Counting: O(n) time, O(1) space for fixed alphabet. Option C doesn't account for frequency - "aab" would match "ab" incorrectly.
6
Instead of two count arrays, we can use one. How?
Answer: Count s, then verify against t by decrementing
Build counts from s (increment). Then process t (decrement). If any count goes negative, t has a char that s doesn't have enough of → not anagram. If all counts are zero at end → anagram.
Solution
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
for c in t:
count[ord(c) - ord('a')] -= 1
if count[ord(c) - ord('a')] < 0:
return False
return True
Complexity Analysis
| Time | O(n) |
|---|---|
| Space | O(1) |
Master This Pattern
Build intuition with interactive MCQs. Practice Hash Set / Hash Map problems in the LeetEye app.
Download LeetEye Free