Ransom Note Problem
Description
LeetCode Problem 383.
Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- 1 <= ransomNote.length, magazine.length <= 10^5
- ransomNote and magazine consist of lowercase English letters.
Solution
Approach: Count the Letters
Each letter of magazine can be used once, so only how many of each letter it has matters, not where they are. Since there are just 26 lowercase letters, an array of 26 counters is enough.
- If
ransomNoteis longer thanmagazine, it cannot be built. - Count every letter of
magazine. - Go through
ransomNote. For each letter, if its counter is already0, the magazine has run out of that letter, so returnfalse. Otherwise use one copy by decrementing the counter. - If every letter was found, return
true.
Checking the counter before decrementing it is what makes repeated letters work: for ransomNote = "aa", magazine = "ab", the first a takes the only copy and the second one finds the counter at 0.
Complexity: O(m + n) time, where m and n are the lengths of ransomNote and magazine, and O(1) extra space (26 counters).
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
letter_count = [0] * 26 # how many of each letter the magazine still has
for ch in magazine:
letter_count[ord(ch) - ord("a")] += 1
for ch in ransomNote:
index = ord(ch) - ord("a")
if letter_count[index] == 0:
return False # this letter is used up
letter_count[index] -= 1
return True
Now write it from memory
Close the write-up and solve it yourself against the tests.