DEV Community

Discussion on: Solving Puzzles With High-Performance JavaScript

Collapse
 
khushbu_thakur profile image
KHUSHBU THAKUR

What about this solution for jewels problem?

function findTotal(J, S) {
return Array.from(S).filter(item => J.indexOf(item) !== -1).length;
}

Collapse
 
healeycodes profile image
Andrew Healey • Edited

That's a great solution 👍. However, as we see here, indexOf has a complexity of O(N). This means that for every stone, we might have to check the whole jewels string rather than a data structure we've constructed.

For example, say we are passed 100 stones and 1000 jewels. With indexOf, the rough number of operations is stones * jewels, or 100 * 1000. What we really want is stones * Set#has, or 100 * 1. Set#has cost.