From e56bbeddd3aae9e0f179b744d4196296a1364a89 Mon Sep 17 00:00:00 2001 From: Tanishq sharma <166993496+tvnisxq@users.noreply.github.com> Date: Sun, 10 Aug 2025 00:36:19 +0530 Subject: [PATCH] Create jewelsAndStones.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added another Leetcode solution to a Problem from topic π—¦π˜π—Ώπ—Άπ—»π—΄π˜€ --- .../jewelsAndStones.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Strings/Jewels & Stones- LC 771 /jewelsAndStones.py diff --git a/Strings/Jewels & Stones- LC 771 /jewelsAndStones.py b/Strings/Jewels & Stones- LC 771 /jewelsAndStones.py new file mode 100644 index 0000000..2aa3a43 --- /dev/null +++ b/Strings/Jewels & Stones- LC 771 /jewelsAndStones.py @@ -0,0 +1,34 @@ +from collections import defaultdict +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + ''' + Brute Force Approach: + If n = len(stones) & m = len(jewels) + β–· Time: O(n.m) -> Iterating through stones and jewels once. String lookup is linear + β–· Space: O(1) -> Only a variable count is used. + ''' + count = 0 + # Iterating through string literal stones character by character + for stone in stones: + # if that very character is also present in the string literal jewels. + if stone in jewels: + count += 1 # Increment the count varaible by 1. + return count + + + + ''' + Optimal Approach: O(1) constant time lookup to check is something is in the set. + β–· Time: O(n+m): + - n for set creation + m for iterating through stones string literal & doing O(1). + β–· Space: O(n) : + - because of n jewels which store n characters if all are unique. + ''' + setJewels = set(jewels) # {'a', 'A',...} + # count variable to keep track of stones which are jewels as well. + count = 0 + + for stone in stones: + if stone in setJewels: + count += 1 + return count