Kth largest with a heap
Return the kth largest integer, counting duplicates. k is between 1 and the input length. Use O(k) auxiliary space.
import heapq
heap = [3, 5]
heapq.heappush(heap, 4)
heapq.heappop(heap)
print(heap[0])Reason about the state
Keep a min-heap containing the k largest values seen. Its root is the smallest of that retained set, so it is the kth largest overall. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the kth largest integer, counting duplicates. k is between 1 and the input length. Use O(k) auxiliary space.
The explanation opens here once every check passes.