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
Determine if a ransom note can be constructed from the letters available in a magazine. Each letter in the magazine can be used at most once. Count the frequency of each character in the magazine, then decrement counts for each character needed in the ransom note. If any character runs out, the note cannot be constructed.
First pass counts magazine letters. Second pass checks ransom note letters against available counts. If a letter is missing or exhausted, return false. The magazine supplies a limited pool of each character that can be spent by the note.
Time complexity is O(M + R), space complexity is O(k) where k is the alphabet size (26 for lowercase).
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.
