InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Ransom Note

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug