← Back to DSA Animator
Valid Anagram LC #242 Easy Frequency Count
Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses the same characters with the same frequencies.

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⁴ | lowercase English letters only
Try Examples
Custom:
Approach
Single frequency array — increment for s, decrement for t
If lengths differ → false immediately. One pass: freq[s[i]]++, freq[t[i]]--. All zeros → anagram. O(n) time, O(1) space (26 slots).
Dual String Strips
s
t
Index Operation
s[i] → freq++
t[i] → freq--
Frequency Map (non-zero entries)
Variables
i
s[i]
t[i]
freq≠0
0
result
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
If |s| ≠ |t| → immediately return false
2
Create freq[26] (or map), all zeros
3
For each i: freq[s[i]]++ and freq[t[i]]--
4
After loop: if any freq[c] ≠ 0 → return false
5
All zeros → return true
Time
O(n)
Space
O(1)
Why This Works

Incrementing for s and decrementing for t in the same pass is like subtracting their character counts. If they are anagrams, every count cancels to zero. Any leftover non-zero entry means one string has a character the other lacks.