↓Skip to main content
  1. LeetCode/

LeetCode 771: Jewels and Stones

·1 min· ·
LeetCode Easy Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-06

  • Submissions: Accepted → Runtime Error ×2 → Accepted

Approach
#

Turn jewels into a set and check each stone in O(1) (Hash Table). Case matters.

My Attempts
#

The two REs used the old parameter names J and S (NameError); renaming to jewels and stones fixed it.

Solution
#

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        jewel_set = set(jewels)
        return sum(s in jewel_set for s in stones)

Complexity
#

Time O(n + m), space O(m).

Mistakes to Avoid
#

  • Uppercase and lowercase are different stones.

Interview Explanation
#

I put jewels in a set and count the stones that appear in it, in O(n + m).

Related

LeetCode 748: Shortest Completing Word
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 748 note: count the plate’s letters in lowercase, then find the shortest word covering every count, taking the earliest on ties
LeetCode 599: Minimum Index Sum of Two Lists
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 599 note: map list1’s strings to indices, sum both indices while scanning list2, and keep every string with the minimum sum
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes
LeetCode 387: First Unique Character in a String
·1 min
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 note: count first, then scan left to right for the first character with count 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains