Code Logo

Ransom Note

Published at16 Mar 2026
Easy 9 views
Like0

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

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

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

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