BudiBadu Logo

Ransom Note

Hash Table Easy 0 views
Like0

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine. Each letter in magazine can only be used once.

The hash table idea is direct: count how many times each character appears in magazine, then spend those counts while walking through ransomNote. If any character runs out, the construction is impossible.

Budibadu uses this problem to reinforce counting and decrementing patterns, which come up all the time in string problems built on maps.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false
Explanation: The letter a does not exist in the 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 two a 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;
    }
}