Problem Description
Given two strings ransomNote and magazine, determine whether ransomNote can be constructed using the letters from magazine. Each letter in magazine can only be used once.
Key Insights
- Use a hash table (or dictionary) to store the frequency of each character present in magazine.
- Iterate over every character in ransomNote and check if the corresponding count in the hash table is available and sufficient.
- Decrease the character count for every match; if any character count falls below zero, return false.
- If all characters in ransomNote can be accounted for, return true.
Space and Time Complexity
Time Complexity: O(n + m), where n is the length of magazine and m is the length of ransomNote. Space Complexity: O(1), since the extra space required for the hash table is limited to at most 26 entries for lowercase English letters.
Solution
We construct a frequency map for the magazine string using a hash table. This frequency map records how many times each letter appears in magazine. Then we iterate through the ransomNote string, and for every letter, we check the corresponding frequency in the map. If a letter is not found or its frequency is zero, we immediately return false as it means the letter cannot be used to build the note. Otherwise, we decrement the frequency count by one. If we successfully process all characters in ransomNote, then it can be constructed from magazine, and we return true.