Jewels and Stones
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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".
Examples
Example 1
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2
Input: jewels = "z", stones = "ZZ"
Output: 0
Constraints
1 <= jewels.length, stones.length <= 50jewelsandstonesconsist of only English letters.- All the characters of
jewelsare unique.
Solution
Method 1 – Hash Set Lookup
Intuition
We want to count how many stones are jewels. By storing all jewel types in a set, we can check each stone in constant time.
Approach
- Store all characters from
jewelsin a set for fast lookup. - Iterate through each character in
stones. - For each stone, if it is in the set, increment the count.
- Return the count.
Code
C++
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
unordered_set<char> s(jewels.begin(), jewels.end());
int ans = 0;
for (char c : stones) if (s.count(c)) ++ans;
return ans;
}
};
Go
func numJewelsInStones(jewels, stones string) int {
s := map[rune]struct{}{}
for _, c := range jewels {
s[c] = struct{}{}
}
ans := 0
for _, c := range stones {
if _, ok := s[c]; ok {
ans++
}
}
return ans
}
Java
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set<Character> s = new HashSet<>();
for (char c : jewels.toCharArray()) s.add(c);
int ans = 0;
for (char c : stones.toCharArray()) if (s.contains(c)) ans++;
return ans;
}
}
Kotlin
class Solution {
fun numJewelsInStones(jewels: String, stones: String): Int {
val s = jewels.toSet()
return stones.count { it in s }
}
}
Python
def num_jewels_in_stones(jewels: str, stones: str) -> int:
s = set(jewels)
return sum(c in s for c in stones)
Rust
use std::collections::HashSet;
fn num_jewels_in_stones(jewels: &str, stones: &str) -> i32 {
let s: HashSet<char> = jewels.chars().collect();
stones.chars().filter(|c| s.contains(c)).count() as i32
}
TypeScript
class Solution {
numJewelsInStones(jewels: string, stones: string): number {
const s = new Set(jewels);
let ans = 0;
for (const c of stones) if (s.has(c)) ans++;
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(m + n)— m is the length of jewels, n is the length of stones. - 🧺 Space complexity:
O(m)— For the set of jewels.