Last Updated: 8 Jan, 2022

Treasure and Jewels

Easy
Asked in company
Amazon

Problem statement

Ninja luckily found a treasure hidden in his backyard. He found some stones in the treasure box and Ninja thought that these stones could be valuable. He went to a stone expert, and the expert gave him a list ‘JEWELS’ consisting of the names of all valuable jewels. Ninja made the list ‘STONES’ of all stones he found in the treasure. All stones and Jewels are represented by English characters. Now, Ninja wants to know the number of jewels he found in the treasure box. Can you help the Ninja?

Note: ‘JEWELS’ consist of distinct characters and ‘A’ and ‘a’ are treated as two different stone types.

For Example
If ‘STONES’ is “abAAc” and JEWELS is “Acd”.The number of jewels Ninja have is 3.
Input Format:
The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains two integers, ‘N’ denoting the number of stones and M denoting the number of Jewels.

The second line of each test case contains an string of size N denoting ‘STONES’

The third line of each test case contains an string of size M denoting ‘JEWELS’
Output Format:
For each test case, print an single integer denoting the number of jewels Ninja found in the treasure box.

Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10000.
1 <= M <= 52 

Time Limit = 1 sec

Approaches

01 Approach

In this approach, for each character in ‘STONES’ , we will iterate the ‘JEWELS’ string and check if the stone is a jewel or not. If we found a jewel, we will increment the ‘ANS’.

At last, we will return the ‘ANS’ corresponding to the number of jewels Ninja found.

 

Algorithm:

 

  • Set ‘ANS’ as 0.
  • For ‘CH’  in ‘STONES’,do the following:
    • For i in ‘JEWELS’:
      • If i is equal to CH:
        • Found a jewel.
        • Set ‘ANS’ as ‘ANS’ + 1.
        • Break.
  • Return ‘ANS’.

02 Approach

In this approach, we will store all the characters of ‘JEWELS’ into a map, so that we can check if a stone is a jewel or not in constant time. First, we will set the value of M[ch] as 1 for all characters of the ‘JEWELS’ string. After that, we will iterate through the ‘STONES’ and if M[ch] is equal to 1, we will increment the ‘ANS’.

 

Algorithm:

  • Declare a map ‘M’.
  • For ch in ‘JEWELS’:
    • Set M[ch] as 1.
  • Declare ‘ANS’ to store the final answer.
  • Set ‘ANS’ as 0.
  • For ch in ‘STONES’:
    • If M[ch] is equal to 1:
      • Set ‘ANS’ as ‘ANS’ + 1.
  • Return ‘ANS’.