Ransom Note (LeetCode 383): Solution and Explanation
You get a note and a magazine, both lowercase strings. Return true if every letter of the note can be cut out of the magazine, using each magazine letter at most once.
Intuition
Picture actually making the note: you cut letters out of the magazine and glue them down. Where a letter sat in the magazine does not matter, only whether a copy is still available when you need it.
So the magazine is really a bag of letters. Count how many of each letter it has. With only lowercase English letters, 26 counters are enough.
Then walk the note. Every letter spends one counter. If a counter is already at zero when the note asks for that letter, the magazine has run out and the note cannot be finished.
A quick check up front helps too: a note with more letters than the whole magazine can never work.
Approach: Count then spend
- If
len(ransomNote) > len(magazine), return false. - Create
counts, an array of 26 zeros. - For each letter in
magazine, incrementcounts[letter]. - For each letter in
ransomNote, ifcounts[letter]is 0 return false; otherwise decrement it. - If the loop finishes, every letter was found. Return true.
Step-by-step example
ransomNote = "a", magazine = "b"
- The note has 1 letter and the magazine has 1, so the length check passes.
- Counting the magazine puts a single 1 in the bin for 'b'. Every other bin, including 'a', stays at 0.
- The note asks for 'a'. Its bin is 0, so there is nothing to cut out.
- The function returns false.
Code: Python, Java, C++
1class Solution:
2 def canConstruct(self, ransomNote: str, magazine: str) -> bool:
3 if len(ransomNote) > len(magazine):
4 return False
5 counts = [0] * 26
6 for ch in magazine:
7 counts[ord(ch) - ord('a')] += 1
8 for ch in ransomNote:
9 idx = ord(ch) - ord('a')
10 if counts[idx] == 0:
11 return False
12 counts[idx] -= 1
13 return True1class Solution {
2 public boolean canConstruct(String ransomNote, String magazine) {
3 if (ransomNote.length() > magazine.length()) {
4 return false;
5 }
6 int[] counts = new int[26];
7 for (char ch : magazine.toCharArray()) {
8 counts[ch - 'a']++;
9 }
10 for (char ch : ransomNote.toCharArray()) {
11 int idx = ch - 'a';
12 if (counts[idx] == 0) {
13 return false;
14 }
15 counts[idx]--;
16 }
17 return true;
18 }
19}1class Solution {
2public:
3 bool canConstruct(string ransomNote, string magazine) {
4 if (ransomNote.size() > magazine.size()) {
5 return false;
6 }
7 int counts[26] = {0};
8 for (char ch : magazine) {
9 counts[ch - 'a']++;
10 }
11 for (char ch : ransomNote) {
12 int idx = ch - 'a';
13 if (counts[idx] == 0) {
14 return false;
15 }
16 counts[idx]--;
17 }
18 return true;
19 }
20};Time and space complexity
O(m + n)
The magazine is scanned once to count letters and the note is scanned once to spend them. Each step is a constant-time array update.
O(1)
The count array always has 26 slots no matter how long the inputs are.
Other approaches
Hash map counter (time O(m + n), space O(k) for k distinct characters)
Use a dictionary or Counter instead of a fixed array. This also handles any character set, such as Unicode, at the cost of hashing overhead.
Sort both strings (time O(m log m + n log n), space O(m + n))
Sort the note and the magazine, then walk them with two pointers, skipping magazine letters that are smaller than the current note letter. It works but sorting makes it slower than counting.
Remove from the magazine string (time O(n * m), space O(m))
For each note letter, find it in the magazine and delete it. Simple to write, but every search and delete costs O(m), so it is quadratic.
Common mistakes
- Counting the note and only checking that each letter appears in the magazine at all. The magazine must have at least as many copies as the note needs.
- Swapping the roles of the two strings. The counts come from the magazine and are spent by the note.
- Decrementing before checking for zero, which lets a count go negative and hides the failure unless you check afterwards.
- Indexing the array with the raw character code instead of
ch - 'a', which runs past the 26 slots.
Frequently asked questions
Why is the space O(1) when I build an array?
The array has exactly 26 slots for the 26 lowercase letters. Its size never grows with the input, so it counts as constant space.
Does the order of letters in the magazine matter?
No. Any letter can be cut from anywhere in the magazine, so only the number of copies of each letter matters.
Can I count the note instead and compare two arrays?
Yes. Count both strings and check that the note's count for every letter is at most the magazine's. It is the same O(m + n) work; spending counts just lets you stop at the first missing letter.
What is the time complexity of Ransom Note?
O(m + n), where m and n are the magazine and note lengths, with O(1) extra space for the 26 counters.