Overview
Given two strings ransomNote and magazine, return true if ransomNote can be constructed using the letters from magazine. Each letter in magazine can only be used once.
Constraints
1 <= ransomNote.length, magazine.length <= 100,000- Both consist of lowercase English letters.
Examples
canConstruct("a", "b"); // => false
canConstruct("aa", "ab"); // => false
canConstruct("aa", "aab"); // => trueSolution
Reveal solution
function canConstruct(ransomNote, magazine) {
const freq = {};
for (const c of magazine) freq[c] = (freq[c] || 0) + 1;
for (const c of ransomNote) {
if (!freq[c]) return false;
freq[c]--;
}
return true;
}Resources
ransom-note.js
Ransom Note
easycodingAlgorithmsHash Map
Overview
Given two strings ransomNote and magazine, return true if ransomNote can be constructed using the letters from magazine. Each letter in magazine can only be used once.
Constraints
1 <= ransomNote.length, magazine.length <= 100,000- Both consist of lowercase English letters.
Examples
canConstruct("a", "b"); // => false
canConstruct("aa", "ab"); // => false
canConstruct("aa", "aab"); // => trueSolution
Reveal solution
function canConstruct(ransomNote, magazine) {
const freq = {};
for (const c of magazine) freq[c] = (freq[c] || 0) + 1;
for (const c of ransomNote) {
if (!freq[c]) return false;
freq[c]--;
}
return true;
}Resources
NameTopicDifficulty
103 of 103 problems