algoadvance

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.

Example:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

Clarifying Questions:

  1. Are the strings jewels and stones always non-empty?
    • Yes, for the sake of this problem, you can assume they are non-empty.
  2. Do the strings contain only alphabetic characters?
    • Yes, both jewels and stones contain only alphabetic characters and are case-sensitive.
  3. Can there be duplicate characters in the jewels string?
    • No, the jewels string contains unique characters.

Strategy:

  1. Set Conversion for Jewels: Convert the jewels string into a set for O(1) average-time complexity lookups.
  2. Count Matching Stones: Iterate through each character in stones and count how many of these characters are present in the jewels set.

Code:

def numJewelsInStones(jewels: str, stones: str) -> int:
    jewels_set = set(jewels)  # Step 1: Convert 'jewels' to a set
    count = 0
    
    for stone in stones:  # Step 2: Iterate through 'stones'
        if stone in jewels_set:
            count += 1
    
    return count

Time Complexity:

Explanation with Example:

For the input jewels = "aA" and stones = "aAAbbbb"

Try our interview co-pilot at AlgoAdvance.com