2 minute read

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example 1:

Input: ransomNote = “a”, magazine = “b” Output: false Example 2:

Input: ransomNote = “aa”, magazine = “ab” Output: false Example 3:

Input: ransomNote = “aa”, magazine = “aab” Output: true

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function (ransomNote, magazine) {
  let ransom = "";
  for (let i = 0; i < ransomNote.length; i++) {
    if (magazine.charAt(i) !== ransomNote.charAt(i)) {
      return false;
    } else {
      console.log(ransom);
      ransom += ransomNote.charAt(i);
    }
  }

  if (ransom === ransomNote) {
    return true;
  }
};

I couldn’t solve this problem, I got an error when I submit my code. That’s because I compare each ransomNote’s character from first letter. The code I will attach below this line would use three methods in array prototype.

var canConstruct = function (ransomNote, magazine) {
  const arr = magazine.split("");
  for (let i = 0; i < ransomNote.length; i++) {
    if (arr.indexOf(ransomNote[i]) === -1) {
      return false;
    } else {
      arr.splice(arr.indexOf(ransomNote[i]), 1);
    }
  }
  return true;
};

The code starts by converting the magazine string into an array called arr using the split method. A for loop is used to iterate through each character of the ransomNote string. Inside the loop, the code checks if the current character of the ransomNote is present in the arr array using the indexOf method. If the character is not found (indexOf returns -1), it means the character is missing in the magazine, and the function immediately returns false.

If the character is found in the arr array, the code uses splice to remove the character from the array. This simulates taking that character from the magazine and ensures that each character can only be used once.

After iterating through all characters of the ransomNote string, if no missing characters were found, the function returns true, indicating that the ransom note can be constructed.

I could learn array methods splice, indexOf and split from the above code written by others.

splice method allows me to modify an array by adding or removing elements at a specified position.

indexOf method allows me to find the index of a specified element within an array.

split method allows me to split a string into an array of substrings based on a specified delimiter

Leave a comment