Magicsheet logo

Ransom Note

Easy
72.2%
Updated 6/1/2025

Ransom Note

What is this problem about?

The Ransom Note problem asks whether you can construct the ransom note string using only letters from the magazine string (each letter used at most once). This easy coding problem tests character frequency matching. The hash table, counting, and string interview pattern is demonstrated.

Why is this asked in interviews?

Apple, Uber, Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe ask this as a quick frequency matching warm-up. It validates the fundamental "can set A be built from set B" frequency comparison pattern.

Algorithmic pattern used

Frequency comparison. Count character frequencies in magazine. For each character in ransomNote: decrement its count in magazine. If any count goes negative, return false. Return true if all checks pass.

Example explanation

ransomNote="aab", magazine="aab". Freq in magazine: {a:2,b:1}.

  • 'a': count a becomes 1. ✓
  • 'a': count a becomes 0. ✓
  • 'b': count b becomes 0. ✓ Return true.

ransomNote="aa", magazine="ab". Freq: {a:1,b:1}. 'a'→0✓. 'a'→-1 ✗. Return false.

Common mistakes candidates make

  • Using set membership instead of frequency count (misses duplicates).
  • Not handling case sensitivity.
  • Checking if magazine contains characters instead of if it has enough of each.
  • Using Python Counter subtraction without checking negative counts.

Interview preparation tip

Ransom Note establishes the "frequency map comparison" pattern that appears in many interview problems: anagram check, permutation in string, group anagrams. Always count frequencies with a hash map or array of size 26, then compare. This O(m+n) approach is both time and space optimal for this problem family.

Similar Questions