One idea
A heap is for priority. Use it when the problem repeatedly asks for the smallest, largest, earliest, or highest-priority item while data changes.
If you only need one final sorted list, sort. If you need the next best item many times, use a heap.
Where heaps fit
A heap gives fast access to one extreme: min or max. In Python, heapq is a min-heap. In Java, PriorityQueue is a min-heap by default.
Common interview clues: kth largest, top K frequent, merge K sorted lists, meeting rooms, running median, shortest path later in graphs. The word priority may not appear.
Cost check
Heap push and pop cost O(log n). Peeking at the top costs O(1). Building a heap from an existing list costs O(n).
For top K, a heap of size K often beats sorting the full array. Sorting n items is O(n log n). A size K heap across n items is O(n log K).
Pick the heap
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Common mistake
Do not use a heap just because the problem says top or kth. If input is tiny in an interview dry run, many solutions work. You must explain cost.
Also remember: a heap is not sorted. Only heap[0] is guaranteed to be the current best item. Do not print the heap list as sorted output.
Top K largest
This version keeps only K numbers in the heap. That is the interview point: do not store more than needed.
Add this to your repo as code/heaps/top_k_largest.py or similar.
import heapq
def top_k_largest(nums, k):
if k <= 0:
return []
heap = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
def test_top_k_largest():
assert top_k_largest([3, 1, 5, 12, 2, 11], 3) == [12, 11, 5]
assert top_k_largest([5, 5, 5], 2) == [5, 5]
assert top_k_largest([9, 1], 0) == []
if __name__ == "__main__":
test_top_k_largest()
print("ok")Use AI carefully
You can ask ChatGPT or Gemini: “Give me three interview problems where a heap beats sorting, with time complexity and one edge case each.”
Check the answer. It should mention O(log n) push or pop, O(1) peek, and why the heap size may stay K. If it says the heap is sorted, fix that note.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done