Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Jewels and Stones in Python
The Jewels and Stones problem is a classic programming challenge where we need to count how many stones are actually jewels. Given a string J representing jewel types and string S representing stones, we count how many characters in S appear in J. The comparison is case-sensitive.
For example, if J = "aZc" and S = "catTableZebraPicnic", we need to count occurrences of 'a', 'Z', and 'c' in the stones string.
Method 1: Using Dictionary (Hash Set)
Create a dictionary to store jewel types for O(1) lookup, then iterate through stones ?
class Solution:
def numJewelsInStones(self, J, S):
jewels = {}
for jewel in J:
jewels[jewel] = 1
count = 0
for stone in S:
if stone in jewels:
count += 1
return count
# Test the solution
solution = Solution()
result = solution.numJewelsInStones("aZc", "catTableZebraPicnic")
print(f"Number of jewels found: {result}")
Number of jewels found: 7
Method 2: Using Python Set
Convert jewels string to a set for more efficient lookup ?
def count_jewels_in_stones(jewels, stones):
jewel_set = set(jewels)
return sum(1 for stone in stones if stone in jewel_set)
# Test the function
J = "aZc"
S = "catTableZebraPicnic"
result = count_jewels_in_stones(J, S)
print(f"Jewels: {J}")
print(f"Stones: {S}")
print(f"Count: {result}")
Jewels: aZc Stones: catTableZebraPicnic Count: 7
Method 3: One-Line Solution
Using list comprehension with sum() for a concise solution ?
def count_jewels_oneline(jewels, stones):
return sum(stone in jewels for stone in stones)
# Test with multiple examples
examples = [
("aA", "aAAbbbb"),
("z", "ZZ"),
("aZc", "catTableZebraPicnic")
]
for jewels, stones in examples:
count = count_jewels_oneline(jewels, stones)
print(f"Jewels: '{jewels}' | Stones: '{stones}' | Count: {count}")
Jewels: 'aA' | Stones: 'aAAbbbb' | Count: 3 Jewels: 'z' | Stones: 'ZZ' | Count: 0 Jewels: 'aZc' | Stones: 'catTableZebraPicnic' | Count: 7
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Dictionary | O(J + S) | O(J) | Good |
| Set | O(J + S) | O(J) | Better |
| One-line | O(J × S) | O(1) | Excellent |
Conclusion
Use the set-based approach for optimal performance with O(J + S) time complexity. For small inputs, the one-line solution offers excellent readability. The dictionary method provides explicit control over the lookup process.
