Hacker Rank Ransom Note Problem

Here’s my solution to the Ransom Note problem found here:
https://www.hackerrank.com/challenges/ctci-ransom-note/problem

The title explicitly points out that it should be solved with a hash table. My logic is in the isViableCombination function. The checkMagazine function just formats the output the way that the test is expecting to receive it (with console.logs).

function checkMagazine(magazine, note) {
   if(isViableCombination(magazine, note)) {
      console.log(‘Yes’);
   } else {
      console.log(‘No’);
   }
}
function isViableCombination(magazine, note) {
   if(note.length > magazine.length) {
      return false;
   }
   let words = new Map();
   for(leti=0;i<magazine.length;i++) {
      let value = words.get(magazine[i])
      if(!value) {
         words.set(magazine[i], 1);
      } else {
         words.set(magazine[i],value + 1);
      }
   }
   for(letj=0;j<note.length;j++){
      let value = words.get(note[j]);
      if(!value) {
         return false;
      } else {
         words.set(note[j],value – 1);
      }
   }
   return true;
}
If the magazine has fewer words in it than the ransom note, then you know off the bat that it won’t work for that particular ransom note.
Complexity is O(m + n). (If m is the length of the magazine and n is the length of the ransom note.)

Leave a Reply