⚡Flashcard Drill➔
NeetCode #70LC-383EasyArrays & Hashing
← Back to All Problems

#70 · #383 · Ransom Note(赎金信)

📌 Problem Statement & Constraints

Given two strings ransomNote and magazine, return true if ransomNote can be constructed using the letters of magazine, each used at most once. Constraints: 1 <= ransomNote.length, magazine.length <= 10^5, all lowercase letters.

💡 Core Algorithmic Approaches

  1. Count the letters available in magazine.
  2. Walk through ransomNote, decrementing the available count for each required letter.
  3. If any letter's count would drop below zero, the note cannot be built.
  4. This is the classic multiplicity-aware membership test; a set comparison would be insufficient.

💻 Benchmark Python3 Implementation

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        from collections import Counter
        avail = Counter(magazine)
        for ch in ransomNote:
            if avail[ch] == 0:
                return False           # letter exhausted or absent
            avail[ch] -= 1
        return True


# Compact equivalent using Counter subtraction
class Solution2:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        from collections import Counter
        return not (Counter(ransomNote) - Counter(magazine))

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m + n): one pass over each string.
💾 Space Complexity
O(k) for the counter, with k <= 26, so O(1) in terms of the alphabet.

⚠️ Interview Pitfalls & Follow-ups

  • Using set(ransomNote) <= set(magazine): this ignores multiplicity, so magazine = "a" would wrongly allow ransomNote = "aa".
  • Iterating magazine instead of ransomNote: you must verify that every needed letter is available, not the other way round.
  • Forgetting the length check: it is not needed here, since the counter approach already catches the case, but an early len(ransomNote) > len(magazine) exit is a cheap optimisation.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

赎金信

给你两个字符串:ransomNote 和 magazine,判断 ransomNote 能不能由 magazine 里面的字母构成。如果可以,返回 true;否则返回 false。magazine 中的每个字母只能在 ransomNote 中使用一次。约束:1 ≤ ransomNote.length, magazine.length ≤ 10^5;两个字符串均由小写英文字母组成。

核心要点

  • 计数比较(标准解) :分别统计两个字符串的字母频次,检查 ransomNote 的每个字母需求都不超过 magazine 的供给。
  • 为什么不能用集合包含 :magazine 中字母数量有限,必须做数量比较。例如 ransomNote = "aa"、magazine = "a" 应返回 False。
  • 优化写法(单表递减) :只建 magazine 的计数表,遍历 ransomNote 时递减,若出现负数则返回 False。这样只需一个表。
  • 空间常数 :字母表固定 26 个,因此空间为 O(1)。

常见陷阱

  • 用 set(ransomNote) &lt;= set(magazine) :只判断字母是否存在,无法处理「数量不足」的情况,是最典型的错误。
  • 提前 return 的判定写成 pool[c] == 0 :应为 &lt; 0 。 == 0 表示恰好用完,仍然合法。
  • 忘记 Counter 对不存在的键返回 0 : pool[c] -= 1 对不存在的 c 会得到 −1 而非抛异常,因此判定 &lt; 0 能正确捕获。

参考实现

from collections import Counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        pool = Counter(magazine)
        for c in ransomNote:
            pool[c] -= 1
            if pool[c] < 0:         # magazine 中该字母不够用
                return False
        return True

# 双表比较写法:
# need, have = Counter(ransomNote), Counter(magazine)
# return all(need[c] <= have[c] for c in need)