#771

Jewels and Stones

Easy
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a HashSet to store jewels for O(1) average time complexity lookups. This reduces the overall time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashSet from the jewels string for fast lookups.
  2. 2Step 2: Initialize a counter to zero to count jewels found in stones.
  3. 3Step 3: For each stone in the stones string, check if it exists in the HashSet of jewels.
  4. 4Step 4: If it exists, increment the counter.
  5. 5Step 5: Return the counter as the result.
solution.py7 lines
1def numJewelsInStones(jewels, stones):
2    jewel_set = set(jewels)
3    count = 0
4    for stone in stones:
5        if stone in jewel_set:
6            count += 1
7    return count

Complexity note: The time complexity is O(n) because we create a HashSet from jewels (O(n)) and then check each stone (O(n)). The space complexity is O(n) due to the HashSet storing the jewels.

  • 1Using a HashSet allows for faster lookups compared to checking each jewel individually.
  • 2Understanding the difference between time complexity and space complexity is crucial for optimizing solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.