Jewels and Stones

Easy Hash Maps

Problem

Given two strings jewels and stones, return the number of stones that are also jewels.

  • 1 ≤ jewels.length, stones.length ≤ 50
  • jewels and stones consist of only English letters
  • All characters in jewels are distinct

Example

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

The algorithm first converts the string jewels into a set for O(1) membership checks. For the stones string, it iterates through each character and checks if it is in the jewel set. Here, 'a' and 'A' are jewels. The stones string contains 'a', 'A', 'A', and four 'b's. Only the 'a' and two 'A's count as jewels, totaling 3.

Approach

Straightforward Solution

A naive approach would check each stone character against every jewel character, resulting in O(n*m) time complexity, which is inefficient for larger inputs.

Core Observation

The problem reduces to counting how many characters in stones are members of the jewels set. Membership queries must be efficient to avoid O(n*m) complexity where n and m are lengths of stones and jewels respectively.

Path to Optimal

Converting jewels into a hash set allows O(1) average-time membership checks. This transforms the problem into a single pass over stones, checking membership in constant time, reducing complexity to O(n + m).

Optimal Approach

Build a set from jewels for constant-time membership checks. Iterate through stones, incrementing a counter each time a stone is found in the jewel set. Return the final count.

Time

O(n + m)

Creating the set from jewels takes O(m), iterating through stones takes O(n), and each membership check is O(1) on average, resulting in linear time overall.

Space

O(m)

The set stores all unique jewel characters, which is at most the length of jewels, requiring O(m) auxiliary space.

Pattern Spotlight

Hash Maps (Set Membership for Counting)

When counting occurrences constrained by membership in a subset, transform the subset into a hash set to enable O(1) membership queries, converting nested membership checks into a single linear pass.

Solution

1class Solution:
2 def numJewelsInStones(self, jewels: str, stones: str) -> int:
3 jewel_set = set(jewels)
4 jewel_count = 0
5
6 for stone in stones:
7 if stone in jewel_set:
8 jewel_count += 1
9
10 return jewel_count

Step-by-Step Solution

1

Build a Set of Jewels for Constant-Time Membership

3jewel_set = set(jewels)

Objective

To create a hash set from the jewels string that allows O(1) average-time membership queries.

Key Insight

Using a set data structure transforms the problem from repeated linear searches for each stone character into constant-time membership checks. This is the key optimization that reduces the overall time complexity from quadratic to linear.

Interview Quick-Check

Core Logic

The set stores all jewel characters, enabling constant-time membership checks during iteration over stones.

Common Pitfalls & Bugs

Using a list or string for membership checks leads to O(n*m) time complexity, which is inefficient for larger inputs.

2

Count Stones That Are Jewels via Single Pass

4jewel_count = 0
6for stone in stones:
7 if stone in jewel_set:
8 jewel_count += 1

Objective

To iterate through each stone and increment the count if it is found in the jewel set.

Key Insight

By checking membership before incrementing, the algorithm efficiently accumulates the total count of jewels present in stones. This single pass leverages the set's O(1) lookup to maintain linear time complexity.

Interview Quick-Check

Core Logic

For each stone character, check if it is in the jewel set and increment the count accordingly.

State & Boundaries

The loop iterates over all stones, ensuring every character is considered exactly once.

Common Pitfalls & Bugs

Failing to check membership before incrementing can lead to incorrect counts or unnecessary increments.

3

Return the Total Count of Jewels Found

10return jewel_count

Objective

To output the final count of stones that are jewels after processing all stones.

Key Insight

Returning the accumulated count completes the problem's requirement. This value represents the total number of stones that match any jewel type.

Interview Quick-Check

Core Logic

Return the accumulated jewel count after processing all stones.

Line Analysis

This solution has 1 Critical line interviewers watch for.

Line 3 Critical
jewel_set = set(jewels)

Create a set from the jewels string for fast membership checks.

This line transforms the jewels string into a hash set, enabling O(1) average-time membership queries, which is essential for efficient counting.

Line 7 Core
if stone in jewel_set:

Check if the current stone is a jewel by membership in the set.

This membership test leverages the set's O(1) lookup to efficiently determine if the stone should be counted.

Line 8 Core
jewel_count += 1

Increment the jewel count when a stone matches a jewel.

Incrementing here accurately tallies the number of stones that are jewels, directly contributing to the final answer.

Line 6 Standard
for stone in stones:

Iterate through each character in the stones string.

This loop ensures every stone is examined exactly once, enabling a linear scan of the input.

Line 10 Standard
return jewel_count

Return the total count of jewels found in stones.

Returning the accumulated count completes the function, providing the correct result as required by the problem.

Line 4 Standard
jewel_count = 0

Initialize the counter for jewels found in stones.

This variable accumulates the total number of stones that are jewels, serving as the final output.

Test Your Understanding

Why is it more efficient to convert jewels into a set before iterating over stones?

Because set membership checks are O(1) on average, converting jewels into a set avoids the need for nested loops, reducing the time complexity from O(n*m) to O(n + m).

Related Problems

Hash Maps pattern

Don't just read it. Drill it.

Reconstruct Jewels and Stones from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Jewels and Stones drill

or drill a free problem