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.
- Cross letters offO(n · m)
- Count the lettersO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 letters each | Verdict |
|---|---|---|---|
| Cross letters off | O(n · m) | Mention it, then move on | |
| Count the letters | O(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
- 1Clarify. Only lower-case letters? Can a magazine letter be used twice? Can the strings be empty?
- 2Give the brute force. Cross off one matching letter per note letter; O(n · m) because each search scans the magazine.
- 3Notice position does not matter. Only the number of copies of each letter matters, so count them.
- 4Code the counts. Fill 26 counters from the magazine, then spend them on the note and stop at the first 0.
- 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?