Skip to content
Problem 771 · LeetCode 771(opens in a new tab)

Jewels and Stones

EasyHash tables

Each letter in jewels names a kind of stone that counts as a jewel. Each letter in stones is one stone you own.

Return how many of your stones are jewels. Case matters: b and B are two different kinds of stone.

Example 1

Input:  jewels = "xY", stones = "xYyYz"
Output: 3
Why:    x, Y and Y are jewels; y and z are not
2 more examples and the constraints

Example 2

Input:  jewels = "q", stones = "QQQ"
Output: 0
Why:    Q is not q, so nothing matches

Example 3

Input:  jewels = "abc", stones = "cab"
Output: 3
Why:    every stone is a jewel

Constraints

  • 1 ≤ length of jewels, length of stones ≤ 50
  • Both strings contain only English letters
  • No letter appears twice in jewels

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan the jewels for every stoneO(J·S)
  2. Jewel setO(J + S)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50 jewels and 50 stonesVerdict
Scan the jewels for every stoneO(J·S)
Works; quadratic
Jewel setO(J + S)
Best; one lookup per stone

J = length of jewels, S = length of stones.

Edge cases to test

  • Case differs. jewels = "q", stones = "QQQ" gives 0.
  • Every stone is a jewel. The answer is the length of stones.
  • Repeated stones. Each copy counts: "aaaa" with jewel "a" gives 4.
  • One letter each. jewels = "Z", stones = "Z" gives 1.

Common mistakes

  • Lowercasing both strings, which merges kinds that the problem keeps apart.
  • Counting jewel kinds found instead of stones, so repeated stones count once.
  • Forgetting to break after a match in the nested loop. Harmless here since jewels are unique, but a bug if they were not.

How to talk through it

  1. 1Clarify. Is the match case sensitive? Can jewels repeat a letter?
  2. 2Give the nested loop. For each stone scan the jewels; that is O(J·S).
  3. 3Speed up the lookup. A set makes each check O(1), so the whole thing is O(J + S).
  4. 4Code it. Build the set, then count stones it contains.
  5. 5Test out loud. Run the case-mismatch and repeated-stone examples before you finish.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?