DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Can Construct

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function (ransomNote, magazine) {
  let mapRansom = new Map();
  let mapMagazine = new Map();
  let canBeCreated = false;

  for (let i = 0; i < magazine.length; i++) {
    if (mapMagazine.has(magazine[i])) {
      mapMagazine.set(magazine[i], mapMagazine.get(magazine[i]) + 1);
    } else {
      mapMagazine.set(magazine[i], 1);
    }
  }
  for (let i = 0; i < ransomNote.length; i++) {
    if (mapRansom.has(ransomNote[i])) {
      mapRansom.set(ransomNote[i], mapRansom.get(ransomNote[i]) + 1);
    } else {
      mapRansom.set(ransomNote[i], 1);
    }
  }
  for (let j = 0; j < ransomNote.length; j++) {
    if (
      mapMagazine.has(ransomNote[j]) &&
      mapMagazine.get(ransomNote[j]) >= mapRansom.get(ransomNote[j])
    ) {
      canBeCreated = true;
    } else {
      canBeCreated = false;
      break;
    }
  }

  return canBeCreated;
};

console.log(
  canConstruct("bg", "efjbdfbdgfjhhaiigfhbaejahgfbbgbjagbddfgdiaigdadhcfcj")
);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)