Skip to main content
←Architecture WorkspaceArchOSWorkspaces/
Sign in
ALGORITHM CANVAS · BINARY MIN-HEAP · TIME O(N log K) · SPACE O(K)
Min-Heap Top-K Selection (Binary Heap)
Maintain a size-K min-heap. The root holds the smallest of the top-K winners; any larger element evicts the root in O(log K).
HEAP TREE (3 ACTIVE NODES)51229
STEP 1/5 · L6
nums=[12,5,29,7,42,18,31]k=3x=29heap=[5,12,29]
PYTHON 3.12 · INSTANT PREVIEW
1import heapq
2
3def top_k_stream(nums, k):
4 heap = []
5 for x in nums:
6 heapq.heappush(heap, x)
7 if len(heap) > k:
8 heapq.heappop(heap)
9 return sorted(heap, reverse=True)