Jewels and Stones - Problem
Imagine you're a treasure hunter who has collected a bag of various stones during your adventure. You also have a jeweler's guide that tells you which types of stones are actually precious jewels!
Given two strings:
jewels- represents the types of stones that are considered jewels (each character is a jewel type)stones- represents all the stones you have collected (each character is a stone you own)
Your task is to count how many of your stones are actually jewels. Note that the problem is case-sensitive, meaning 'a' and 'A' are considered different types of stones.
Goal: Return the total count of stones that are also jewels.
Input & Output
example_1.py โ Basic Case
$
Input:
jewels = "aA", stones = "aAAbbbb"
โบ
Output:
3
๐ก Note:
The stones 'a', 'A', and 'A' are jewels (case-sensitive). The stones 'b' are not jewels.
example_2.py โ No Matches
$
Input:
jewels = "z", stones = "ZZ"
โบ
Output:
0
๐ก Note:
Since the problem is case-sensitive, 'z' and 'Z' are different. No stones match the jewels.
example_3.py โ All Matches
$
Input:
jewels = "abc", stones = "aabbcc"
โบ
Output:
6
๐ก Note:
All stones are jewels: 2 'a's, 2 'b's, and 2 'c's = 6 total jewels.
Constraints
- 1 โค jewels.length, stones.length โค 50
- jewels and stones consist of only English letters
- jewels has no duplicate characters
- Both strings are case-sensitive
Visualization
Tap to expand
Understanding the Visualization
1
Prepare Reference
Create a quick-lookup reference (hash set) of all jewel types
2
Process Collection
Go through each stone in your collection once
3
Quick Check
For each stone, instantly check if it's a jewel using the reference
4
Count Results
Tally up all the jewels found in your stone collection
Key Takeaway
๐ฏ Key Insight: Converting the jewels into a hash set enables O(1) lookup time instead of O(m) linear search, reducing overall complexity from O(nรm) to O(n+m)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code