Jewels and Stones — LeetCode 771 Python Solution
- Problem
- #771
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- jewels = "aA", stones = "aAAbbbb"
- Output
- 3
Python solution
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
s = set(jewels)
return sum(c in s for c in stones)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 771. Jewels and Stones is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 771. Jewels and Stones?
- LeetCode 771. Jewels and Stones is rated Easy on LeetCode.
- What is the time complexity of LeetCode 771. Jewels and Stones?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 771. Jewels and Stones?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 771. Jewels and Stones cover?
- LeetCode 771. Jewels and Stones is tagged Hash Table and String on LeetCode.