← Back
Data StructureIntermediate
⛰️
Heaps
Priority-based tree structure
⏱️ 5–7 hours🧩 10 LeetCode
🔒 Login to unlock solutions and track progress. Login
What is it?
A heap is like a hospital waiting room — the most urgent patient always goes next, regardless of when they arrived.
- Min-Heap — smallest value is always at the top (root)
- Max-Heap — largest value is always at the top
Used as a Priority Queue: insert in O(log n), get the top in O(1).
Real-World Examples
Hospital triage system
CPU task scheduler
Top-K most frequent words
Running median stream
Dijkstra shortest path
Event-driven simulation
Code Example
What this code shows
Turn [3,1,4,1,5,9,2] into a min-heap — the smallest value (1) rises to the top. Pop it off, and the next smallest becomes the new top. Push 0 and it immediately claims the top spot.
// JS has no built-in heap; simulate with a sorted array
const heap = [3, 1, 4, 1, 5, 9, 2];
heap.sort((a, b) => a - b); // sort ascending = min-heap order
console.log("Min value: ", heap[0]); // 1 — smallest at front
heap.shift(); // pop the minimum (removes index 0)
console.log("After pop, top: ", heap[0]); // 1 — next smallest
heap.push(0); // insert 0 into heap
heap.sort((a, b) => a - b); // re-sort to maintain heap property
console.log("After push(0), top:", heap[0]); // 0 — new smallestExpected Output
Min value: 1 After pop, top: 1 After push(0), top: 0