🔗 Problem Link
LeetCode 383 – Ransom Note
👉 https://leetcode.com/problems/ransom-note/
Introduction
This is a classic frequency-count problem that tests your understanding of:
- Character counting
- HashMap usage
- Greedy validation logic
At first glance, the problem looks very simple — but it’s a very common interview question because it checks whether you can think in terms of resource usage.
Here:
magazine→ available resourcesransomNote→ required resources
We must check if the available letters are sufficient to construct the ransom note.
📌 Problem Understanding
You are given:
ransomNotemagazine
Rules:
- Each letter in
magazinecan be used only once. - Return
trueif ransomNote can be formed. - Otherwise return
false.
Example 1
Example 2
Example 3
🧠 Intuition
The logic is straightforward:
- Count frequency of each character in
magazine. - For each character in
ransomNote: - Check if it exists in the map.
- Check if its frequency is greater than 0.
- Reduce frequency after using it.
- If at any point we cannot use a character → return false.
This is a greedy approach.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Build Frequency Map from Magazine
We count how many times each character appears in the magazine.
2️⃣ Check Each Character in Ransom Note
For every character in ransomNote:
3️⃣ Validate Availability
If:
- Character exists in map
- Frequency is still available
Then reduce its count:
Otherwise:
Immediately stop if we cannot construct.
🎯 Why This Works
We treat:
magazineas supplyransomNoteas demand
We reduce supply every time we use a character.
If supply runs out → construction fails.
⏱ Complexity Analysis
Time Complexity: O(n + m)
- One pass to build map from magazine
- One pass to check ransomNote
Space Complexity: O(26) ≈ O(1)
Only lowercase English letters.
🔥 Even Better Optimization – Using Array Instead of HashMap
Since we know:
- Only lowercase letters are allowed
We can use an integer array of size 26.
This is faster and more memory-efficient.
Optimized Version
This avoids HashMap overhead.
🏁 Final Thoughts
This problem reinforces:
- Frequency counting pattern
- Greedy character usage
- Early exit for optimization
- Using arrays instead of HashMap when character set is limited
It’s a foundational problem that appears often in interviews.
If you master this pattern, you can easily solve:
- Valid Anagram
- Find the Difference
- Check if All Characters Have Equal Occurrences
- Permutation in String




