DSA AnimatorDSA animations
Ransom NoteLC #383EasyHashing · Char Count
Problem

Given two strings ransomNote and magazine, return true if ransomNote can be constructed using the letters from magazine (each letter can be used only once).

Example 1
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints: 1≤ransomNote.length,magazine.length≤10⁵  |  Lowercase letters only
Try Examples
Custom:
Approach
Character Frequency Count
Count each letter's frequency in magazine. Then for each letter in ransomNote, decrement that count. If a count goes below 0 → not enough of that letter → return false.
Magazine (source letters)
Ransom Note (to construct)
Alphabet Frequency Array
Variables
Phase
—
char
—
count
—
result
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Count each letter's frequency in magazine (int[26])
2
For each letter in ransomNote: decrement its count
3
If count drops below 0 → not enough letters → return false
4
All letters satisfied → return true
Time
O(m+n)
Space
O(1)
Why It Works

We only need letter frequencies — not order. Magazine provides a "budget" of each letter. Each letter used in the ransom note consumes one unit from that budget. If any budget goes negative, we can't build the note.

How to solve Ransom Note

LeetCode 383 · Easy · Arrays · Pattern: Frequency Count

Why the obvious approach is slow

Searching the magazine for each note letter, and removing it, is O(n·m). Counting letters is much faster.

The key idea

Count how many of each letter the magazine has. Then go through the note, using up one count per letter. If any count would go below 0, the note is impossible.

Remember

"can I build this" problems are letter counts. Add from the supply, subtract for the demand, and watch for negatives.

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

More Arrays problems