383. Ransom Note
At a Glance
- Topic: Hash Table
- Pattern: Hash Map
- Difficulty: Easy
- LeetCode: 383
Problem Statement
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters 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 <= 105
ransomNote and magazine consist of lowercase English letters.Approach & Solution Steps
Count the frequencies of characters in the magazine using a hash map or array. Iterate through the ransom note, decrementing the counts. If a count drops below zero, return false.
Optimal JS Solution
function canConstruct(ransomNote, magazine) {
const counts = {};
for (const char of magazine) {
counts[char] = (counts[char] || 0) + 1;
}
for (const char of ransomNote) {
if (!counts[char]) return false;
counts[char]--;
}
return true;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?