DSA AnimatorDSA animations
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.

How to solve Valid Anagram

LeetCode 242 · Easy · Strings · Pattern: Frequency Count

Why the obvious approach is slow

The simplest approach sorts both strings and compares them. It works, but sorting takes O(n log n). We can do it in O(n).

The key idea

Count how many times each letter appears. Add 1 for every letter of s. Subtract 1 for every letter of t. If every count ends at 0, the strings are anagrams. And if the lengths differ, return false right away.

Remember

Anagram means equal letter counts. One array of 26 counts: add for s, subtract for t.

Run the animation above on your own input, or watch the 1:39 video explanation of Valid Anagram with a dry run and Java code.

More Strings problems