Back to Problem
Official 1867 views

Editorial: Ransom Note

by admin ·

32

1 Intuition

It is a multiset containment check.

2 Approach

Count magazine letters, then consume one count per note letter, failing if any count runs out.

3 Complexity Analysis

Time O(n + m), Space O(1).

4 Solution Code

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        have = {}
        for c in magazine:
            have[c] = have.get(c, 0) + 1
        for c in ransomNote:
            if have.get(c, 0) == 0:
                return False
            have[c] -= 1
        return True

5 Code Walkthrough

The reference solution below implements the approach step by step.