Amazon Interview Question
Software Engineer / DevelopersCountry: India
htt p : // stackoverflow.com/questions/4922648/how-we-can-find-kth-largest-element-from-a-max-heap-in-ok-time
The link gives the answer of kth largest from a max heap ... doesn't seem much complicated ... traverse the heap for 1st k values and compare. (would be same for kth smallest in a min-heap) But what if the question was 'kth smallest from max-heap' (a heap by default is max heap unless mentioned otherwise). is it still possible in O(k)? please give an algo if possible
@topcoder99, Are you missing any data point? Array based heap does not make any difference unless it is a max-heap or a min-heap. Otherwise for a general array, finding the Kth smallest element will itself take O(nlogk) time complexity.
See "quickselect" or something like that. There are also deterministic versions of that algorithm.
Now how to do it in O(k) time, I'm not really sure...I only have O(k log k).
- Ilya.Rudyak June 06, 2016