SDE & MLE Prep

383. Ransom Note

Problem

Decide whether ransomNote can be spelled with letters cut from magazine, using each letter of magazine at most once.

Example: ransomNote = "aa", magazine = "aab" → true; ransomNote = "aa", magazine = "ab" → false

Constraints: lowercase English letters.

Count the magazine's letters once; every letter of the note must be available that many times.

Complexity: O(m + n) time, O(1) space (26 letters).

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        have = Counter(magazine)
        return all(have[c] >= k for c, k in Counter(ransomNote).items())