Leetcode 771. Jewels and Stones

Today we are going to solve Leetcode 771. Jewels and Stones

Photo by James Harrison on Unsplash

Problem Statement

You’re given strings representing the types of stones that are jewels, and representing the stones you have. Each character in is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so is considered a different type of stone from .

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

Example 2:

Input: jewels = "z", stones = "ZZ"
Output: 0

Constraints:

  • and consist of only English letters.
  • All the characters of are unique.

Solution

As we can see from the problem statement, this is a problem for finding the occurrence of one character in another string. Here we are asked to find the number of stones that are jewels. We are given the Jewels and Stones. Therefore, what we can do is that we can add the jewels in an and count the number of stones that are also jewels. We are using because with , we can find an entry in time. The code can be found below.

Time Complexity: O(n), n is the length of the stones string

Space Complexity: O(m), m is the length of the jewels string

Tech-enthusiastic . Connect me — https://twitter.com/sourav__saikia

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store