Grokking the Coding Interview: The Original Course
0% completed
Problem 5: Ransom Note (easy)
Problem Statement
Given two strings, one representing a ransom note and the other representing the available letters from a magazine, determine if it's possible to construct the ransom note using only the letters from the magazine. Each letter from the magazine can be used only once.
Examples:
-
Example 1:
- Input: Ransom Note = "hello", Magazine = "hellworld"
- Expected Output: true
- Justification: The word "hello" can be constructed from the letters in "hellworld".
-
Example 2:
- Input: Ransom Note = "notes", Magazine = "stoned"
.....
.....
.....
Like the course? Get enrolled and start learning!
Dominik Myszkowski
· 5 days ago
class Solution { canConstruct(ransomNote, magazine) { // ToDo: Write Your Code Here. if (ransomNote.length > magazine.length) return false; const map = new Map(); for (const c of magazine) { map.set(c, (map.get(c) ?? 0) + 1); } for (const c of ransomNote) { if (!map.has(c) || map.get(c) <= 0) return false; map.set(c, map.get(c) - 1); } return true; } }
Jitesh Golatkar
· 2 years ago
Show 1 reply
Reading Progress
0%