Sorting finds the k-th largest number, but a heap does it with less memory when k is small.
What to build
A program that prints the k-th largest number of a list using a heap of size k.
Requirements
- Count repeated numbers separately.
- Use
heapq; the heap must never hold more than k numbers.
Input
The first line has n and k. The second line has the n integers.
Output
The k-th largest number.
Constraints
1 ≤ k ≤ n ≤ 10⁵.
Example
Input:
6 2
3 2 1 5 6 4
Output:
5
Why it works
A min-heap of size k keeps the k largest numbers seen so far, because anything smaller than all of them is popped. Its smallest element is therefore the k-th largest. The cost is O(n log k).
Examples
6 2 3 2 1 5 6 4
5
9 4 3 2 3 1 2 4 5 5 6
4
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep a min-heap (heapq) with at most k numbers: push each number and pop the smallest when the size reaches k + 1.
Hint 2
After all numbers, the smallest in the heap, heap[0], is the k-th largest.
Hint 3
Repeated values count separately: in 5 5 4, the 2nd largest is 5.
Solution
Show one correct solution (try it yourself first)
import heapq
n, k = map(int, input().split())
nums = list(map(int, input().split()))
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
print(heap[0])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step