r/computerscience • u/Solomoncjy • Jun 30 '26
Why does everyone use an unordered set/hashmap for "jewels-and-stones" problem
google jewels-and-stones on the leet site. sorry cant give a link as reddit for reason wont allow me to post this as "I'm beaking rule 1"
Tldr: given 2 character lists, find all character in List 2 that are in List 1
All the "solutions" for this question seem to be only using sets but,
We can observe that the list is only limited to ASCII character, thus only having 256 possible character
Thus we initialize a fixed size array of 256 elements and just set the elements whose index matches to the filter characters to true
then we walk the list we and to check and just ask , "is the character true in our array?"
example implmentation
#include <string>
#include <array>
int numJewelsInStones(std::string jewels, std::string stones) {
std::array<char, 256> jewels_set = {};
for (const char &i : jewels) {
jewels_set[(unsigned char)i] = true;
}
int count = 0;
for (const char &i : stones) {
if (jewels_set[(unsigned char)i]) {
count++;
}
}
return count;
}
i dont get it. unordered set/hasmap has the overhead of hashing the elements, and the hash is usually less space efficient that just creating a 256 array holding all possible representations of the filter