Explain heaps.
Skip to solutionKEEP THE
mediumDSA
What is a heap / priority queue?
711 views
01
Understand the problem
heappriority-queue
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
A heap is a complete binary tree maintaining the heap property (min-heap: parent ≤ children). It gives O(1) peek of min/max and O(log n) insert/extract — backing priority queues. Useful for top-k problems, Dijkstra's algorithm, and scheduling.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
k largest with a heap
Run Playgroundimport heapq
def k_largest(nums, k):
heap = [] # min-heap of size k
for n in nums:
heapq.heappush(heap, n)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return sorted(heap, reverse=True)
# --- demo --- (or the built-in: heapq.nlargest(k, nums))
print(k_largest([3, 1, 5, 12, 2, 11], 3)) # [12, 11, 5]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 54 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.