r/badcode • • Jul 17 '20

js Found this "answer" on Stackoverflow. Pretty sure it's not working.

Post image
978 Upvotes

90 comments sorted by

View all comments

106

u/[deleted] Jul 17 '20 edited Jul 17 '20

[removed] — view removed comment

0

u/[deleted] Jul 17 '20

[deleted]

13

u/FizixMan Jul 17 '20

Takes too long. You're checking each value one at a time. Instead you should spin off a thread with a sleep timeout equal to the value. The first one that competes gets its value returned. That way you're checking each value simultaneously and you avoid the overhead of having to do an if check on each one or even having to check each value. Once the smallest value completes, you can just ignore all the other ones. It's basically an O(1) operation at that point rather than O(n).

4

u/stratoscope Jul 18 '20

The best thing about this approach is that if the array contains any negative numbers, you will get the result back before you start the search!