Ransom Note
Hashing
Problem Statement
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed from magazine
and false
otherwise.
Example
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Solution (Hash Map)
We can solve this by counting the characters in the magazine. Then, for each character in the ransom note, we check if it's available in our magazine counts and decrement the count.
Algorithm Steps
- Create a hash map (or an array of size 26) to store the frequency of characters in the `magazine`.
- Iterate through the `magazine` string and populate the frequency map.
- Iterate through the `ransomNote` string.
- For each character, check if it exists in the frequency map and its count is greater than 0.
- If not, return `false`. Otherwise, decrement the character's count in the map.
- If the loop completes, it means the ransom note can be constructed. Return `true`.
Magazine Character Counts
Ransom Note
a
a
b
Start. Count characters in the magazine.
Ransom Note Solution