Ransom Note - 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.

Input & Output

Example 1 — Basic Case
$ Input: ransomNote = "a", magazine = "b"
Output: false
💡 Note: Magazine doesn't contain the letter 'a', so ransom note cannot be constructed
Example 2 — Sufficient Letters
$ Input: ransomNote = "aa", magazine = "aab"
Output: true
💡 Note: Magazine contains 2 'a's and 1 'b', which is enough to construct "aa"
Example 3 — Insufficient Letters
$ Input: ransomNote = "aab", magazine = "baa"
Output: true
💡 Note: Magazine has 2 'a's and 1 'b', exactly what we need for "aab"

Constraints

  • 1 ≤ ransomNote.length, magazine.length ≤ 105
  • ransomNote and magazine consist of lowercase English letters.

Visualization

Tap to expand
Ransom Note: Can We Cut Letters From Magazine?Ransom Note: "aa"aaMagazine: "aab"aabMagazine has 2 a's and 1 b → Enough for ransom note "aa"true
Understanding the Visualization
1
Input
Ransom note and magazine strings
2
Process
Check if magazine has enough letters
3
Output
True if construction possible, false otherwise
Key Takeaway
🎯 Key Insight: Count magazine letters first, then verify ransom note doesn't exceed available counts
Asked in
Amazon 15 Facebook 8
156.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen