You are given two strings: the ransom note you want to build and the magazine you are allowed to cut letters from.
Each character in the magazine can be used at most once. That means it is not enough for a letter to exist somewhere in the magazine; it has to exist enough times to cover the note.
For example, ransomNote = "a" and magazine = "b" returns false because the needed letter does not exist. ransomNote = "aa" and magazine = "ab" is also false because there is only one 'a'. But ransomNote = "aa" and magazine = "aab" returns true.
So the question is whether the magazine has enough copies of every character required by the note.
Example Input & Output
The needed character does not exist in magazine.
There is only one a available.
The magazine provides enough characters.
Algorithm Flow

Solution Approach
Count the available letters in the magazine with a hash map.
Then walk through the ransom note one character at a time. For each character, check whether the map still has at least one copy left. If not, return false immediately. Otherwise decrement that count and continue.
If you make it through the whole ransom note, every required character was available, so return true. This runs in O(m + n) time.
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 Challenge.
