1 minute read

You’re given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so “a” is considered a different type of stone from “A”.

Example 1:

Input: jewels = “aA”, stones = “aAAbbbb” Output: 3 Example 2:

Input: jewels = “z”, stones = “ZZ” Output: 0

/**
 * @param {string} jewels
 * @param {string} stones
 * @return {number}
 */
var numJewelsInStones = function (jewels, stones) {
  // Initialize a new set by taking 'jewels'.
  const jSet = new Set(jewels);
  // Initialize a variable to keep track of how many jewel in stones
  let result = 0;

  // Loop through each word in stones
  for (let stone of stones) {
    // Use if conditional weather jewelSet words include in stones string or not.
    if (jSet.has(stone)) {
      // if so, add to 1 to result variable
      result++;
    }
  }
  // Return result.
  return result;
};

The time complexity of this function is O(n), where ‘n’ is the number of characters in the ‘stones’ array. This is because it iterates through each character in the stones array once.

Leave a comment