Loading W Code...
Manage priorities efficiently with Max-Heaps and Min-Heaps.
5
Topics
40
Minutes
O(log n)
Insertion
Top-K
Best For
Imagine an emergency room triage counter. Patients are not treated strictly in the order they arrive; instead, patients with high-severity injuries are prioritized and treated first.
A Heap is a specialized tree-based data structure that satisfies the heap ordering property, serving as the foundation for Priority Queues.
≥) the values of its children. The absolute largest element resides at the root.≤) the values of its children. The absolute smallest element resides at the root.A heap is structured as a Complete Binary Tree—all levels are packed fully, except possibly the bottom level, which is filled from left to right. This structural constraint allows a heap to be represented efficiently as a flat, contiguous Array, mapping relationships using simple arithmetic indexes:
// Array Representation
// For a node at index 'i':
int parent = (i - 1) / 2;
int leftChild = 2 * i + 1;
int rightChild = 2 * i + 2;When modifying a heap, we temporarily violate the ordering property. To restore it, we perform heapification:
O(log n) Time)O(log n) Time)0).void push(int val) {
heap.push_back(val);
int i = heap.size() - 1;
while(i > 0) {
int p = (i - 1) / 2;
if(heap[p] < heap[i]) {
swap(heap[p], heap[i]);
i = p;
} else break;
}
}The C++ Standard Template Library provides a built-in container adapter, std::priority_queue, configured as a heap:
priority_queue<int> pq;priority_queue<int, vector<int>, greater<int>> min_pq;push(val): Inserts an item into the priority queue (O(log n)).pop(): Removes the top item (O(log n)).top(): Returns a reference to the top item (O(1)).#include <queue>
using namespace std;
int main() {
// Max Heap
priority_queue<int> pq;
pq.push(10);
pq.push(30);
pq.push(20);
cout << pq.top(); // 30
pq.pop(); // Removes 30
// Min Heap
priority_queue<int, vector<int>, greater<int>> min_pq;
min_pq.push(10);
min_pq.push(30);
cout << min_pq.top(); // 10
}Heap Sort is a comparison-based sorting algorithm that operates directly on the input array, avoiding extra memory allocations:
O(n) time using bottom-up heapification).O(n log n) time in the best, average, and worst cases, and sorts in-place using O(1) auxiliary space.void heapSort(vector<int>& arr) {
// 1. Build Heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// 2. Extract elements
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]); // Move current root to end
heapify(arr, i, 0); // Fix reduced heap
}
}Heaps are the optimal data structure for solving problems that ask for the "Top K" largest or smallest elements:
O(n log K) Time)K.K, pop the smallest element.K largest elements remain in the heap.O(n log K) Time)K.K, pop the largest element. This discards larger values, keeping only the K smallest elements.// K Largest Elements
priority_queue<int, vector<int>, greater<int>> minHeap;
for(int num : nums) {
minHeap.push(num);
if(minHeap.size() > k) {
minHeap.pop(); // Remove smallest
}
}
// Heap now has K largest