AAlgoLoopSpaced repetition for LeetCode
EASYHash Map / SetLeetCode ↗

Ransom Note

The key idea

Count how many of each letter the magazine has, then spend those letters on the note. The note is buildable exactly when the magazine has at least as many of every letter as the note needs. Each magazine letter is used at most once, so a simple frequency tally answers it in one pass.

Problem

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.

Constraints

Examples

Input: ransomNote = "a", magazine = "b" Output: false
Input: ransomNote = "aa", magazine = "ab" Output: false
Input: ransomNote = "aa", magazine = "aab" Output: true

Complexity

Time: O(m + n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems