sagelearnai

Ransom Note

Difficulty: Easy · Pattern: Hashing · LeetCode #383

Return true if ransomNote can be built using letters from magazine, each magazine letter used at most once.

Examples

text
ransomNote = "aa", magazine = "aab"  →  true
ransomNote = "aa", magazine = "ab"   →  false

Hints

  1. Count the available letters, then consume them.

Approach

Count letters in magazine (26 slots or a Counter). For each letter of the note, decrement its count; if it would go negative, return false. O(m + n).

Complexity

Time: O(m + n). Space: O(1) (26 counts).

Python solution
from collections import Counter

def canConstruct(ransomNote, magazine):
    have = Counter(magazine)
    for ch in ransomNote:
        if have[ch] == 0:
            return False
        have[ch] -= 1
    return True
JavaScript solution
function canConstruct(ransomNote, magazine) {
  const have = new Array(26).fill(0);
  for (const ch of magazine) have[ch.charCodeAt(0) - 97]++;
  for (const ch of ransomNote) if (--have[ch.charCodeAt(0) - 97] < 0) return false;
  return true;
}