Skip to content
Problem 383 · LeetCode 383(opens in a new tab)

Ransom Note

EasyHash tables

You have two strings of lower-case letters: ransomNote, the text you want to write, and magazine, the letters you can cut out.

Each letter in the magazine can be cut out and used at most once. Return true if you can spell the whole note this way, and false if you cannot.

Example 1

Input:  ransomNote = "tot", magazine = "tote"
Output: true
Why:    the magazine has two t and one o; the e is unused
2 more examples and the constraints

Example 2

Input:  ransomNote = "bee", magazine = "beb"
Output: false
Why:    the note needs two e, the magazine has only one

Example 3

Input:  ransomNote = "k", magazine = "xyz"
Output: false
Why:    there is no k to cut out

Constraints

  • 1 ≤ length of each string ≤ 100,000
  • Both strings use only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Cross letters offO(n · m)
  2. Count the lettersO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 letters eachVerdict
Cross letters offO(n · m)
Mention it, then move on
Count the lettersO(n + m)
Best; two passes, 26 counters

n = length of ransomNote, m = length of magazine.

Edge cases to test

  • Repeated letter in the note. "bee" needs two e; one e in the magazine is not enough.
  • Note longer than the magazine. It can never be built, whatever the letters.
  • Same string. "abc" from "abc" uses every letter exactly once: true.
  • Letter missing entirely. "k" from "xyz" is false on the first letter.

Common mistakes

  • Checking only that each note letter appears in the magazine, not how many times.
  • Counting the note and the magazine the wrong way round.
  • Using a set, which forgets how many copies of a letter there are.

How to talk through it

  1. 1Clarify. Only lower-case letters? Can a magazine letter be used twice? Can the strings be empty?
  2. 2Give the brute force. Cross off one matching letter per note letter; O(n · m) because each search scans the magazine.
  3. 3Notice position does not matter. Only the number of copies of each letter matters, so count them.
  4. 4Code the counts. Fill 26 counters from the magazine, then spend them on the note and stop at the first 0.
  5. 5Test out loud. Run a repeated letter, a missing letter and a note longer than the magazine.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?