We are given two strings ransomNote and magazine. We are required to calculate if the ransomNote can be built using the magazine. You may use a character only x times while building ransomNote, if it occurs x+n times where n>=0.
Whenever we talk about character counts in a string, the first instinct must be hashmaps. Hashmaps allow us to store how may times a character has occurred in a string.
Code:
Java
Big O Analysis
Runtime
The runtime complexity here is O(N*M) - where N is the hashmap size and M is the ransomNote string length. While iterating over the hashmap (O(N)), we are also check if ransomNote contains a character (O(M)).
Memory
The memory usage is O(N) where N is the hashmap size OR unique characters in ransomNote and magazine combined.