Ransom Note
Ever seen a movie where characters cut out random letters from magazines to spell out a secret note? In Ransom Note, you're given two strings, ransomNote and magazine. Your task is to return true if you can construct the note using the characters available in the magazine. Each letter in the magazine can only be used once, just like a real clipping!
The "secret sauce" here is a Frequency Map. Think of it as your character inventory. First, count how many of each letter you have in the magazine. As you walk through your note, you "spend" those counts. If you try to use a letter you don’t have, or one you’ve already run out of, the note becomes impossible to finish! This approach gives you a linear time complexity of O(n + m), which is much faster than searching for each individual letter. It’s an elegant, fast, and professional way to handle inventory-style lookup problems!
For text and token tasks, be precise with index movement and substring boundaries. Most hidden failures come from partial-match handling and boundary cuts, so keep comparisons explicit and avoid assumptions about implicit separators or formatting not guaranteed by the input contract.
Examples
The needed character does not exist in magazine.
There is only one a available.
The magazine provides enough characters.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public boolean ransom_note(String ransomNote, String magazine) {
Map<Character, Integer> count = new HashMap<>();
for (char ch : magazine.toCharArray()) count.put(ch, count.getOrDefault(ch, 0) + 1);
for (char ch : ransomNote.toCharArray()) {
if (!count.containsKey(ch) || count.get(ch) == 0) return false;
count.put(ch, count.get(ch) - 1);
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
