One way to find to find the th smallest element in a list is to first sort the list, and then take the th element in the sorted list.
However, sorting has a minimum worst-case runtime of Is it possible to find the th smallest element with worst-case runtime
Bonus: Prove your answer!
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
No need to worry...just hash all the elements in an array. For rest, look at the below python code.
Here I considered that the array has duplicates. This just takes O(n) in the worst case, which I fixed 10^7 is the upper bound. This won't work if the array contains negative numbers.