Ransom Note

Easy

Topics
Hash TableStringCounting

Given two strings s (the ransom note) and t (the magazine), return true if s can be constructed using the letters of t. Each letter of t can be used at most once.

Example 1

noteaa
magazineaab
Every character of the note is available in the magazine, counting multiplicity — a letter needed twice must appear twice. One count of the magazine then one decrementing pass over the note settles it. Answer: true.
Top row is the note; below it the magazine it is cut from.
Input:  s = "aa", t = "aab"
Output: true

Example 2

noteaa
magazineab
The shaded characters run out of supply in the magazine, so the answer is false.
Input:  s = "aa", t = "ab"
Output: false

Constraints

  • 1 <= s.length, t.length <= 10^5
  • s and t consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

We can build the note if the magazine supplies at least as many of each letter as the note needs. Order is irrelevant, so this is a multiset containment question: count the magazine's letters, then spend them against the note.

Counting the magazine and decrementing per note character fails fast on the first letter that runs out, and never needs a second structure.

Approach

  1. Count each character of the magazine.
  2. For each character of the note, fail if its remaining count is zero, else decrement.

Dry Run

note = "aa", magazine = "aab"

counts  a:2  b:1

'a'  count 2 -> ok, now 1
'a'  count 1 -> ok, now 0
true

note = "aa", magazine = "ab"
counts  a:1  b:1
'a'  ok, now 0
'a'  count 0 -> false

Complexity

  • Time — O(s + t): one pass over each string.
  • Space — O(1): the counter holds at most one entry per distinct character, and the constraints restrict both strings to lowercase English letters, so at most 26 entries regardless of the 10^5 length. That is the fixed-alphabet convention and worth saying explicitly — a 26-slot array makes it unmistakable.

Common Pitfalls

  • Counting the note and checking against the magazine, then forgetting that the magazine may legitimately have surplus. The direction matters: spend from the magazine.
  • Comparing sets of distinct characters, which ignores multiplicity — "aa" against "ab" would wrongly pass.
  • Comparing lengths as a shortcut. A longer magazine proves nothing about any individual letter.
  • Using count() inside a loop over the note, which re-scans the magazine per character and is O(s * t).

Full Solution — all languages

class Solution:
    def canConstruct(self, s, t):
        have = {}
        for c in t:
            have[c] = have.get(c, 0) + 1
        for c in s:
            if have.get(c, 0) <= 0:
                return False
            have[c] -= 1
        return True
Asked at Spotify
SensAI
Beta
Tap the mic to stop voice mode