Statement
Solution
Naive approach
A naive approach for this problem is to iterate through each character in the ransom note. For each character, check if it exists in the magazine or not. If it does, we remove that character from the magazine to ensure that each character in the magazine is only used once. If, at any point, we find that a character is not present in the magazine, we return FALSE, indicating that it is not possible to construct a ransom note from the given magazine. If we successfully iterate through all characters in the ransom note, we return TRUE.
We indeed got our desired output. However, this approach is computationally expensive as we have to check the presence of every character of the ransom note in the magazine, giving us the time complexity of
Optimized approach using knowing what to track
An optimized approach to solve this problem is to keep track of the occurrences of characters using the hash map. We store the frequency of each character of the magazine in the hash map. After storing the frequencies, we iterate over each character in the ransom note and check if the character is present in the hash map and its frequency is greater than zero. If it is, we decrement the frequency by
If we successfully iterate through all characters in the ransom note without encountering a character that is not present in the hash map or its frequency is
Let’s look at the illustration to get a better understanding of the solution.