0:00 / 0:00

Can the note be cut from the magazine? Count every magazine letter, then spend one per note letter and fail the moment a count runs out.

▼

The problem

LeetCode 383 (Easy). Given two strings ransomNote and magazine, return true if ransomNote can be built from the letters of magazine, each magazine letter used at most once, and false otherwise. Both strings are lowercase English letters.

Examples (LeetCode's, scene 2): ("a", "b") → false, ("aa", "ab") → false, ("aa", "aab") → true.

TRY IT ON LEETCODE ▶

The solution

def canConstruct(ransomNote, magazine):
    count = [0] * 26
    for ch in magazine:
        count[ord(ch) - ord('a')] += 1
    for ch in ransomNote:
        i = ord(ch) - ord('a')
        if count[i] == 0:
            return False
        count[i] -= 1
    return True

Transcript

Ransom Note. A kidnapper builds a note from letters cut out of a magazine. You get two strings, the note and the magazine. Can the note be built from the magazine's letters? Each magazine letter can be used only once.

Three small cases. Note A, magazine B: false, there's no A. Note A A, magazine A B: false, only one A. Note A A, magazine A A B: true. Both A's are covered, and the B is left over.

The naive way: for each note letter, scan the magazine from the left for an unused copy, and cut it out. Loot from toolbox takes ten checks. With m note letters and n magazine letters, that's up to m times n checks.

But order never matters, only how many of each letter. So count first. Pour the magazine into a type case with twenty-six drawers, one per letter. Toolbox puts three blocks in O, and one each in T, L, B and X. Then spend: each note letter takes a block from its own drawer. A drawer that's empty when you need it means false.

Let's spend loot. L takes the only L. Each O takes a block, leaving one. T takes the only T. Every letter got a block: true, with an O, a B and an X left over. Now try lotto. L, O and T work. But the second T finds its drawer empty. Stop right there: false. The last O is never even checked.

In code, the drawers are an array of twenty-six counters, all zero. One loop over the magazine adds one to each letter's counter. A second loop over the note checks its counter: if it's zero, return false, otherwise subtract one. After the loop, return true.

Each string is read once, so the time is order m plus n. For a thousand letters each, that's two thousand steps instead of up to a million. The case never grows past twenty-six drawers, so the space is constant.

Count the magazine, spend on the note, stop at an empty drawer. That's Ransom Note.