Ransom Note
EasyTop Interview 150 Arrays & HashingCriteoKaratProblem
You are given two strings, ransomNote and magazine. Decide whether
ransomNote can be built using letters cut out of magazine.
Every letter in the magazine can be used at most once, and the order of the letters does not matter.
Return true if the note can be built, otherwise false.
Constraints
- 1 ≤ ransomNote.length, magazine.length ≤ 10⁵
- Both strings use lowercase English letters only
Examples: pick one to animate
Solutions
TimeO(m + r)
SpaceO(1)
Time: One pass over the magazine (m letters) and one pass over the note (r letters), with O(1) work per letter.
Space: The count table has 26 slots, no matter how long the strings are.
Count how many of each letter the magazine has. Then walk through the note: every letter needs a count above zero, and using it takes one away. The first letter with a zero count means the note cannot be built.