Software Engineer (SDE)dsaintermediate3 interactive MCQs in app
Heap / Priority Queue
min-heap of size k for top-k largestO(log n) push/pop vs O(n) heapifyPython min-heap negation for max-heap
Core Concept
A binary heap (priority queue) maintains only a partial parent-<=children invariant inside a flat array (`left = 2i+1`, `right = 2i+2`), giving O(1) peek-min, O(log n) push/pop, and O(n) bottom-up `heapify`. To find the Top-K LARGEST elements in a huge stream of `n` numbers cleanly, keep a **MIN-heap of fixed size `k`** and pop the smallest whenever length exceeds `k`—costing O(n log k) time and O(k) memory instead of O(n log n) full sort!
Worked Example
streaming `[5, 1, 9, 3, 7]` for top `k=2`: keep `[1,5]`, push `9` & pop min `1` -> `[5,9]`, push `3` & pop `3` -> `[5,9]`, push `7` & pop `5` -> `[7,9]` (`heap[0]=7` is 2nd largest!).
Common Pitfall
Python `heapq` is strictly a MIN-heap (push `-x` to simulate a max-heap) and assuming sorting order across siblings at the same depth.
Recommended Readings & Practice
Practice Heap / Priority Queue with 3 graded MCQs & written feedback.
Take SOARDO’s free 12-question diagnostic to see how strong you are across your target role and unlock adaptive daily missions.