BudiBadu Logo

Ransom Note

Hash Table Easy 7 views
Like0

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

Example 1
Input
ransomNote = "a", magazine = "b"
Output
false
Explanation

The needed character does not exist in magazine.

Example 2
Input
ransomNote = "aa", magazine = "ab"
Output
false
Explanation

There is only one a available.

Example 3
Input
ransomNote = "aa", magazine = "aab"
Output
true
Explanation

The magazine provides enough characters.

Algorithm Flow

Recommendation Algorithm Flow for Ransom Note - Budibadu
Recommendation Algorithm Flow for Ransom Note - Budibadu

Best Answers

java
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;
    }
}