Jewels and Stones — Solution in Python, Java & C++
Jewels and Stones solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Jewels and Stones is an easy coding problem on strings and hash table, asked in Amazon, Google, Adobe and Meta interviews.
- Difficulty: Easy
- Topics: Strings, Hash Table
- Asked at: Amazon, Google, Adobe, Meta
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given jewels, a string where each character is a type of stone that counts as a jewel, and stones, a string where each character is a stone you have.
Return how many of your stones are jewels. Letters are case-sensitive, so "a" and "A" are different types.
Example 1
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2
Input: jewels = "z", stones = "ZZ"
Output: 0
Explanation: Case matters.
Example 3
Input: jewels = "abc", stones = "cba"
Output: 3
Constraints
1 <= jewels.length, stones.length <= 40All characters are English letters.The characters of jewels are distinct.
Hints for Jewels and Stones
Hint 1
Put the jewel types into a hash set so each stone is a constant-time lookup.
Hint 2
Then scan the stones once and count the hits.
How to solve Jewels and Stones
Put the jewel types in a hash set, then count stones whose type is in the set.
Approach
- Build a set from
jewels. - Count the characters of
stonespresent in the set.
Why it works
Set membership is O(1), so each stone costs constant time instead of a scan over jewels.
Complexity
- Time —
O(j + s) - Space —
O(j)
Pitfalls
- Case matters —
aandAare different stones.
Reference solution
Python
def numJewelsInStones(jewels: str, stones: str) -> int:
jewel_set = set(jewels)
return sum(1 for ch in stones if ch in jewel_set)Java
public static int numJewelsInStones(String jewels, String stones) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < jewels.length(); i++) set.add(jewels.charAt(i));
int count = 0;
for (int i = 0; i < stones.length(); i++) {
if (set.contains(stones.charAt(i))) count++;
}
return count;
}C++
int numJewelsInStones(string jewels, string stones) {
bool isJewel[128] = {false};
for (char c : jewels) isJewel[(int) c] = true;
int count = 0;
for (char c : stones) {
if (isJewel[(int) c]) count++;
}
return count;
}JavaScript
var numJewelsInStones = function(jewels, stones) {
const set = new Set(jewels.split(""));
let count = 0;
for (let i = 0; i < stones.length; i++) {
if (set.has(stones[i])) count++;
}
return count;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Hashing: Hash Maps and Hash Sets