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 Problem INPUT ransomNote "a" magazine "b" Can we build "a" using letters from "b"? ransomNote = "a" magazine = "b" ALGORITHM STEPS 1 Build Hash Map Count magazine letters {'b': 1} 2 Check Each Letter In ransomNote 3 Look for 'a' in hash map 'a' in {'b': 1} ? NOT FOUND! 4 Return Result Letter missing --> false FINAL RESULT false Cannot construct! Magazine "b" does not contain letter 'a' Output: false Key Insight: Use a hash map to count character frequencies in magazine. For each character in ransomNote, check if it exists in the map with count > 0, then decrement. If any char is missing, return false. Time: O(m + n) | Space: O(k) where k = unique characters in magazine TutorialsPoint - Ransom Note | Hash Map Approach
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