Article start
DSA Course: Interview Patterns and Problem Solving
Module 9: Hashing & Prefix Sum

Ransom Note: Character Availability Pattern

Check whether one string can be built from another using counts.

May 29, 2026·24

Learning Outcome

After this lesson, you should be able to use a frequency table as an availability inventory and consume characters safely.

Problem Statement

Given ransomNote and magazine, return true if ransomNote can be constructed using each magazine character at most once.

InputOutputWhy
ransomNote = "aa", magazine = "aab"trueThe magazine has two a characters, enough to build aa.

Brute Force Approach

For each ransom character, scan the magazine for an unused matching character. This is slow and awkward to track.

Optimized Approach

Count magazine characters once. For each ransom character, decrement its available count and fail immediately if it goes below zero.

Exact Pseudocode

freq = counts of magazine
for ch in ransomNote:
  freq[ch] -= 1
  if freq[ch] < 0:
    return false
return true

Reference Code

class Solution:
    def canConstruct(self, ransomNote, magazine):
        freq = {}
        for ch in magazine:
            freq[ch] = freq.get(ch, 0) + 1

        for ch in ransomNote:
            freq[ch] = freq.get(ch, 0) - 1
            if freq[ch] < 0:
                return False

        return True

Sample Dry Run

StepStateResult
Count magazinea:2, b:1Availability ready
Need first aa count becomes 1Still possible
Need second aa count becomes 0Still possible
FinishNo shortage foundreturn true

Complexity

MeasureValueReason
TimeO(n + m)Both strings are scanned once.
SpaceO(1)For lowercase English letters, the frequency array has fixed size.

Edge Cases

  • An empty ransom note returns true.
  • Repeated needed characters require repeated availability.
  • Set membership alone is not enough.

Interview Checklist

  • Count magazine, not ransomNote, as the available inventory.
  • Fail as soon as a count goes below zero.
  • Use the right character range for the prompt.

FAQs

Why not use a set?

A set only says whether a character exists, not how many copies are available.

Why decrement while scanning ransomNote?

It simulates consuming each required character once.

What is the core pattern?

Frequency availability counting.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.