InterviewPrepKit

Home / Coding / Arrays & Hashing

Ransom Note

easy Original β†—
Solving tips
  • Recognize a multiset-containment question: order is irrelevant, only per-letter counts matter.
  • Count both strings (Counter or a length-26 array) and check need[ch] <= have[ch] for every letter; O(m+n) time, O(1) space for the fixed alphabet.
  • Efficient variant: count the magazine into 26 slots, then decrement while reading the note and fail the instant a slot goes negative.
  • Pitfall: comparing letter sets ignores multiplicity ('aa' vs 'ab' fails), and count the magazine first, then spend with the note (order matters).

Problem

You’re given two strings, ransomNote and magazine. Determine whether you can assemble the ransom note by cutting letters out of the magazine: every character of ransomNote must be matched to a distinct character of magazine (each magazine letter can be used at most once). Return True if it’s possible, False otherwise.

In other words: for every letter, does the magazine contain at least as many copies as the note needs?

Examples

  • Input: ransomNote = "a", magazine = "b" β†’ Output: False The magazine has no a at all.
  • Input: ransomNote = "aa", magazine = "ab" β†’ Output: False The note needs two as but the magazine supplies only one.
  • Input: ransomNote = "aab", magazine = "baa" β†’ Output: True The magazine has two as and one b β€” exactly enough.

Constraints

  • 1 <= len(ransomNote), len(magazine) <= 10^5
  • Both strings consist of lowercase English letters only

Expected: O(m + n) time. The 26-letter alphabet is a strong hint about the counting structure.

Think about it first

Hint 1 Does the *order* of letters in either string matter at all?
Hint 2 If order doesn't matter, the only thing that does is how many of each letter each string has. What structure captures that?
Hint 3 Count each string's letters (a hash map, or a length-26 array since it's only lowercase letters). The note is buildable iff for every letter its note-count ≀ its magazine-count.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.