Code Logo

Jewels and Stones

Published at23 Jul 2026
Easy 2 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

Solution Approach

Count how many stones are also jewels. Jewels are defined by a string of character types. Each stone character is compared against the jewel set. Use a hash set for O(1) lookups so the solution runs in linear time instead of checking each stone against every jewel character.

function numJewelsInStones(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;
}

Build a lookup set from the jewel characters. Then iterate through each stone and check membership in the set. The problem distinguishes between uppercase and lowercase, so 'a' and 'A' are treated as different jewel types.

Time complexity is O(J + S), space complexity is O(J) where J is the jewels string length.

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;
    }
}