LeetCode Problem - Link
I will be solving the Ransom Note problem from LeetCode today, this requires you to utilize a hashmap to solve this. I took a while to solve this perfectly, I spent almost 20 minutes trying to create 2 hashes (god knows for what) and compare them. Took a break, and came back later to get an idea that a single hash map is enough, which emphases that programmers need breaks and I need to remind myself consistently to take breaks when I'm stuck with something. Changing the way you think and attacking a problem from multiple angles is the key to solving them
Hashmaps are pretty useful, it took me a long time (a couple of years) to get used to/comfortable or even understand what a hashmap is. Not until I became a full-time JavaScript developer that I started to think about data in terms of objects.
Simple Hashmap Solution
/** * @param {string} ransomNote * @param {string} magazine * @return {boolean} */ var buildMapFromString = (string) => { // utility function that helps us build a map with count values var map = {} var arr = string.split('') for (var i = 0; i < arr.length; i++) { var stringChar = arr[i] if (map[stringChar]) { map[stringChar] += 1 } else { map[stringChar] = 1 } } return map } var canConstruct = function (ransomNote, magazine) { var magazineMap = buildMapFromString(magazine) var ransomArr = ransomNote.split('') // use this variable to keep track of constructed string length var constructedStringLength = 0 ransomArr.map((ransomChar) => { if (magazineMap[ransomChar]) { magazineMap[ransomChar] -= 1 // when we reduce a number from the map, increment constructedStringLength += 1 } }) // if the final contructed length and ransom note length are same, its a match return constructedStringLength == ransomNote.length };