Sponsored
Sponsored
This approach leverages a Set (or a HashSet in some languages) for quickly determining if a stone is a jewel. The idea is to store all the jewel types in a set, then iterate through each stone, checking if the stone is in the set. If it is, we increment our count of jewels found.
Time Complexity: O(n * m), where n is the number of stones and m is the number of jewels. Space Complexity: O(1), since no extra space is used other than for the input strings.
1function numJewelsInStones(jewels, stones) {
2 const jewelSet = new Set(jewels);
3 let count = 0;
4 for (const stone of stones) {
5 if (jewelSet.has(stone)) {
6 count++;
7 }
8 }
9 return count;
10}
11
12console.log(numJewelsInStones('aA', 'aAAbbbb'));
The JavaScript solution establishes a Set
of jewels and iterates through the stones, incrementing a count for each stone that appears in the set. The use of a set ensures fast membership checking.
This approach uses an array to quickly map each character to an index, allowing us to count frequencies of jewels in the stones. Since the input is restricted to English letters, a fixed-size array of 52 (for each upper and lower case letter) is adequate.
Time Complexity: O(n + m), where n is the length of jewels and m is the length of stones. Space Complexity: O(1), using a fixed-size array for character mapping.
1
In JavaScript, an array of a fixed size 52 is used to map letters to jewel indicators, achieved via charCodeAt()
for index calculations.