Ransom Note
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.
Algorithm Flow

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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
