leetcode-150

Ransom Note

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.


πŸ” Problem Statement

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine, and false otherwise.

Note:

Examples:

canConstruct("a", "b");         // false
canConstruct("aa", "ab");       // false
canConstruct("aa", "aab");      // true

🧠 Core Idea

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.


βœ… JavaScript Solution using a Frequency Map

/**
 * 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;
};

How it works:


🚫 Common Pitfalls


🧩 Optimization Notes

This makes it a fast and efficient solution, perfect for coding rounds.


🧠 Final Thoughts

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!


πŸ”— Reference

LeetCode: Ransom Note