Ransom Note solution explained
To check whether a note can be built from a magazine's letters, with each letter used at most once, count the magazine's letters and then spend them on the note: subtract one for each note character, and fail as soon as a count would go below zero. That is O(m + n) time for the two lengths, with memory bounded by the alphabet. If the note is longer than the magazine, you can say no before counting anything.
By Evin JohnPublished 6 min read
The task, restated
You get two strings: the note you want to write and the magazine you can cut letters from. Every letter you cut can be used once. Return true if you can form the note exactly, and false otherwise. Letters left over in the magazine are fine. The common version uses only lowercase English letters, so ask whether spaces, digits or capitals can appear.
| Note | Magazine | Possible? | Why |
|---|---|---|---|
tea | teacup | Yes | t, e and a are all there; c, u and p are left over |
seed | deserts | Yes | Two e's needed, two available |
book | bok | No | Only one o to cut |
level | velvet | No | Two l's needed, only one available |
| empty note | abc | Yes | Nothing to cut |
How it differs from an anagram check
Both questions count letters, but they ask different things. An anagram check needs the two strings to have exactly the same counts. Here, the magazine only needs at least as many of each letter as the note. In set terms, the note's letters must form a sub-multiset of the magazine's. That changes the code: no length equality, no requirement that the counts end at zero, and the early exit compares lengths the other way.
What the interviewer is looking for
This is a quick warm-up. The interviewer checks that you pick a count table, put the counts on the right string (the magazine is the supply), and know the cost of each approach. A nice touch is choosing which string to count when one is much longer than the other, and explaining why the fixed array is constant space.
Brute force: cut letters one at a time
def can_build_slow(note, magazine):
supply = list(magazine)
for ch in note:
if ch in supply:
supply.remove(ch)
else:
return False
return TrueEach in and remove scans the list, so the cost is the note length times the magazine length. It mirrors the physical act of cutting letters, which makes it a good test reference, but say right away that you will improve it.
Optimal: count the supply, then spend it
Build a count of the magazine's letters. Walk the note and decrease the count of each letter it uses. If a count is already zero when the note asks for another copy, there is not enough of that letter, so return false. If the walk finishes, every letter was available.
def can_build(note, magazine):
if len(note) > len(magazine):
return False
supply = {}
for ch in magazine:
supply[ch] = supply.get(ch, 0) + 1
for ch in note:
if supply.get(ch, 0) == 0:
return False
supply[ch] -= 1
return Truefunction canBuild(note, magazine) {
if (note.length > magazine.length) return false;
const supply = new Array(26).fill(0);
const base = "a".charCodeAt(0);
for (let i = 0; i < magazine.length; i++) {
supply[magazine.charCodeAt(i) - base]++;
}
for (let i = 0; i < note.length; i++) {
const slot = note.charCodeAt(i) - base;
if (supply[slot] === 0) return false;
supply[slot]--;
}
return true;
}In Python, collections.Counter gives a one-line version: not (Counter(note) - Counter(magazine)). Counter subtraction drops counts that fall to zero or below, so an empty result means the magazine covered everything. It is fine to offer, as long as you can explain what it does.
Which string should you count?
The method above counts the magazine and walks the note. The opposite also works: count what the note needs, then walk the magazine ticking letters off, and stop as soon as all needs are met. That version can finish early when a long magazine covers a short note in its first few hundred characters. Both are O(m + n) in the worst case. Saying this shows you think about real inputs, not just the big-O.
Cost of each approach
| Approach | Time | Extra space |
|---|---|---|
| Remove letters from a list | O(m·n) | O(n) |
| Sort both, walk with two pointers | O(m log m + n log n) | O(m + n) for sorted copies |
| Count the magazine, spend on the note | O(m + n) | O(k) |
| 26-slot array | O(m + n) | O(1) |
Edge cases to test
- An empty note: true, whatever the magazine.
- An empty magazine with a non-empty note: false.
- A note longer than the magazine: false at once.
- A letter the note needs twice and the magazine has once.
- Identical strings: true.
- Characters outside a to z when using the 26-slot array: guard them or switch to a dictionary.
Common mistakes
- Counting the note and checking it against the magazine's letters as a set, which ignores how many copies exist.
- Requiring equal counts, which turns the problem into an anagram check and wrongly rejects leftovers.
- Swapping the roles and counting the note as the supply.
- Using
str.countinside a loop for every letter, which hides a quadratic cost. - Putting the length check the wrong way round: it is the note that must not be longer.
How to explain it out loud
Fictional example
- Candidate
- The magazine is my supply. If the note is longer, I can stop right away.
- Candidate
- Otherwise I count the magazine's letters, then walk the note and take one of each letter it needs. If a count is already zero, I return false. Leftovers in the magazine do not matter.
- Candidate
- That is linear in both lengths. For lowercase letters I would use a 26-slot array, so the extra space is constant.
Related problems
Valid Anagram is the equality version of this count. Isomorphic Strings also walks characters with a small table, but tracks structure instead of counts. Minimum Size Subarray Sum and Minimum Window Substring show how a running supply moves inside a window. Find every walkthrough on the coding problems hub.
Natively during warm-up practice
Short problems like this are where you can practice pacing: state the approach, code it, test it, all within a few minutes. In a practice round on Mac or Windows, Natively reads the problem from a screenshot and can offer a code hint, and its transcript shows how long you spent before writing the first line. See the AI assistant for coding interviews page for the full feature list.
Questions people ask
How do you solve Ransom Note?
Count the letters in the magazine, then walk the note and subtract one for each letter it uses. If a letter's count is already zero when needed, return false; otherwise return true.
What is the time complexity of Ransom Note?
O(m + n) for the note and magazine lengths. With a 26-slot array for lowercase letters, the extra space is constant.
How is Ransom Note different from Valid Anagram?
An anagram needs exactly equal letter counts. A ransom note only needs the magazine to have at least as many of each letter, so leftovers are allowed.
Can I use Counter in Python?
Yes: not (Counter(note) - Counter(magazine)) is a correct one-liner, because Counter subtraction drops counts that reach zero or below. Be ready to explain it.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
