EasyHash Maps

Ransom Note

Explanation & Solution

Description

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: ransomNote = "a", magazine = "b"

Output: false

Explanation: The letter 'a' is not available in the magazine.

Constraints

  • 1 <= ransomNote.length, magazine.length <= 10⁵
  • ransomNote and magazine consist of lowercase English letters

Approach

Hash Maps pattern

1. Count Characters in the Magazine

  • Create a hash map charCount to store the frequency of each character in magazine
  • Iterate through every character in magazine and increment its count in the map

2. Verify the Ransom Note

  • Iterate through every character in ransomNote
  • For each character, look up its available count in charCount
  • If the count is 0 or the character doesn't exist, return false immediately — we can't build the note
  • Otherwise, decrement the count by 1 to mark that letter as used

3. Return the Result

  • If we successfully iterate through the entire ransomNote without running out of any letter, return true

Key Insight

  • The hash map lets us efficiently track how many of each letter are available in the magazine and "consume" them one by one as the ransom note needs them
Time
O(m + n) where m is the length of `magazine` and n is the length of `ransomNote`
Space
O(1)the map holds at most 26 lowercase English letters

Solution Code