Coding Interview PatternsRansom Note
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⁵ransomNoteandmagazineconsist of lowercase English letters
Approach
Hash Maps pattern
1. Count Characters in the Magazine
- Create a hash map
charCountto store the frequency of each character inmagazine - Iterate through every character in
magazineand 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
0or the character doesn't exist, returnfalseimmediately — 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
ransomNotewithout running out of any letter, returntrue
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