Jewels and Stones - Problem

You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones 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 "a" is considered a different type of stone from "A".

Input & Output

Example 1 — Basic Case
$ Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
💡 Note: The stones 'a', 'A', and 'A' match jewel types in "aA". The letter 'b' is not a jewel type.
Example 2 — Case Sensitivity
$ Input: jewels = "z", stones = "ZZ"
Output: 0
💡 Note: Since letters are case sensitive, lowercase 'z' is different from uppercase 'Z'. No matches found.
Example 3 — All Match
$ Input: jewels = "abc", stones = "aabbcc"
Output: 6
💡 Note: All stones match jewel types: 'a'(2), 'b'(2), 'c'(2) = 6 total jewels.

Constraints

  • 1 ≤ jewels.length, stones.length ≤ 50
  • jewels and stones consist of only English letters
  • All the characters of jewels are unique

Visualization

Tap to expand
Jewels and Stones - Hash Set Lookup INPUT jewels = "aA" a A stones = "aAAbbbb" a A A b b b b 0 1 2 3 4 5 6 Case Sensitive! 'a' != 'A' ALGORITHM STEPS 1 Create Hash Set Add jewels to set: {a, A} {a, A} 2 Initialize Counter count = 0 3 Iterate Stones Check each in set Stone In Set? Count a YES 1 A YES 2 A YES 3 b,b,b,b NO 3 4 Return Count O(1) lookup per stone FINAL RESULT Jewels found in stones: a MATCH A MATCH A MATCH Non-jewels (b x 4): b b b b Output: 3 OK - Verified! 1(a) + 2(A) = 3 Key Insight: Using a Hash Set for jewels enables O(1) lookup time for each stone check. Total time complexity: O(J + S) where J = jewels length, S = stones length. Space complexity: O(J) for storing the jewels set. TutorialsPoint - Jewels and Stones | Hash Set Lookup Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
95.0K Views
High Frequency
~8 min Avg. Time
4.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen