Kth Largest Element in an Array
Find the k-th largest value in an unsorted list, here the k-th highest water reading.
DSA, Medium, Heap / Priority Queue
Which structure or algorithm, and what does it cost.
A list levels holds water level readings, in no particular order. Return the k-th highest reading. Equal readings count separately, so two readings of 9 are the first and second highest. Return the reading itself, not its position.
Examples
Constraints
- 1 <=
k<= length oflevels<= 150,000. - Each reading is a whole number between -1,000,000,000 and 1,000,000,000.
Your answer must contain
- The simple method and its cost; the heap method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n log k) time and O(k) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Sorting solves it, but ask whether you need the whole list in order or only a small part of it.
Hint 2 the approach
Only the k highest readings matter, and among them you want the smallest. Which structure keeps a small set and gives its smallest at once?
Hint 3 the key step
Keep a min-heap that never holds more than k readings. When must a reading leave, and which one?
Walkthrough
Full walkthrough brute force to best
Brute force
Sort the readings from highest to lowest and take position k. Sorting costs O(n log n) time and O(n) memory. It is correct, and for one question it is fine, but it orders all n readings when only the top k matter.
Better method
Quickselect: pick a pivot and split the readings into those above it, equal to it and below it. If k falls in the above group, continue there. If it falls in the equal group, the pivot is the answer. Otherwise subtract those two sizes from k and continue in the below group. Each step keeps only part of the data, so the average cost is O(n). Bad pivots can make it O(n^2) in the worst case, and the heap method has no such case.
Best method
The answer is the smallest of the k highest readings. Keep a min-heap of at most k readings. For each reading, push it. If the heap holds more than k, pop the root, which is the smallest and cannot be in the top k. At the end the heap holds the k highest readings, and its root is the k-th highest: the other k - 1 are at least as high, and every dropped reading is not higher. Each reading costs O(log k). When k is small, this beats a full sort.
Hand trace
Run on [14, 3, 9, 20, 7] with k = 2. Read 14: the heap holds 14. Read 3: the heap holds 3 and 14. Read 9: push it, the heap holds three readings, so pop 3. The heap holds 9 and 14. Read 20: push it, pop 9. The heap holds 14 and 20. Read 7: push it, pop 7. The heap holds 14 and 20. The root is 14.
Code
import heapq
def kth_highest(levels, k):
heap = [] # min-heap holding the k highest readings
for x in levels:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # the smallest cannot be in the top k
return heap[0]Time and memory
O(n log k) time: each reading costs one push and at most one pop on a heap of at most k + 1 readings. O(k) memory for the heap.
Common mistakes
- Using a max-heap of size k. Its root is the highest reading, but the k-th highest is the smallest of the top k, so you need a min-heap.
- Removing equal readings with a set. Equal readings count separately, so [5, 5, 5, 2] with k = 3 must give 5.
- Counting from the wrong end. Sorting low to high and taking position k gives the k-th lowest reading.
- Popping when the heap reaches k instead of when it passes k. It then keeps k - 1 readings, and k = 1 empties it.