< Back




771. Jewels and Stones

Stupid easy question. We have stones and jewels, identified by lowercase and uppercase characters.
The jewels are unique, the stones are not. How many stones do we have that are also jewels?

Convert jewels to a set to conduct an O(1) lookup. If the stone is in the jewels set, increment the
counter.

The solution is as follows:


  class Solution:
      def numJewelsInStones(self, jewels: str, stones: str) -> int:
          jewels = set(jewels)
          ans = 0

          for stone in stones:
              if stone in jewels: ans += 1

          return ans


_ Time Complexity:

  O(n) - We convert jewels to a set, and we also inspect every stone.

_ Space Complexity:

  O(n) - We store jewels in a set.