The Ransom Note problem is a popular string problem found in coding interviews. It tests your ability to count characters and manage constraints under simple rules. While the problem is conceptually easy, it reveals how well you understand hashing, maps, and character frequency management.
Letβs walk through the problem, the thinking process, and a clean JavaScript solution that makes it crystal clear.
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
, and false
otherwise.
Note:
magazine
can only be used once.canConstruct("a", "b"); // false
canConstruct("aa", "ab"); // false
canConstruct("aa", "aab"); // true
To solve this, we just need to make sure that for each character in the ransomNote
, the magazine
has at least that many of that character.
The simplest way? Count the characters in magazine
, then loop through ransomNote
and reduce the count as we use them. If at any point a character is not available or runs out, return false
.
/**
* Determines if the ransomNote can be constructed from the magazine.
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
const freq = {};
for (const char of magazine) {
freq[char] = (freq[char] || 0) + 1;
}
for (const char of ransomNote) {
if (!freq[char]) return false;
freq[char]--;
}
return true;
};
magazine
.ransomNote
, and for each character:
false
.true
.O(m + n)
, where m
is the length of magazine
, n
is the length of ransomNote
.O(1)
because the character set is limited to lowercase letters (max 26).This makes it a fast and efficient solution, perfect for coding rounds.
The Ransom Note problem is a great way to practice building frequency maps and thinking in terms of resource allocation. Itβs also a good precursor to more complex problems involving hash maps and greedy algorithms.
Try this with different character sets (like Unicode), or extend it to word-level logic for a fun twist!