Code Logo

Jewels and Stones

Published at23 Jul 2026
Easy 0 views
Like0

You are given two strings: jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in the string is a type of stone. Count how many of your stones are also jewels. Letters are case-sensitive, so 'a' is different from 'A'.

A hash set is the natural solution: add all jewel types to a set, then iterate through stones and count how many are in the set. This runs in O(n + m) time where n and m are the lengths of the strings. Without a hash set, you would need to check each stone against each jewel type in O(n * m) time.

This is one of the simplest hash set applications and is a common interview warm-up problem.

The problem may also be solved without a hash set using nested loops or regular expressions, but the hash set approach is the most efficient and the most readable.

Example Input & Output

Example 1
Input
"abc", "abcabc"
Output
6
Explanation

All stones are jewels.

Example 2
Input
"z", "ZZ"
Output
0
Explanation

z != Z.

Example 3
Input
"aA", "aAAbbbb"
Output
3
Explanation

a and A are jewels.

Algorithm Flow

Recommendation Algorithm Flow for Jewels and Stones
Recommendation Algorithm Flow for Jewels and Stones

Solution Approach

Add all jewel chars to a set. Count stones that are in the set.

function solution(jewels, stones) {
  var set = {};
  for (var i = 0; i < jewels.length; i++) set[jewels[i]] = true;
  var count = 0;
  for (var i = 0; i < stones.length; i++) {
    if (set[stones[i]]) count++;
  }
  return count;
}

Time O(n+m), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(String jewels, String stones) {
        Set<Character> set = new HashSet<>();
        for (char j : jewels.toCharArray()) set.add(j);
        int count = 0;
        for (char s : stones.toCharArray()) { if (set.contains(s)) count++; }
        return count;
    }
}