ā°ļø Heap - Priority-Based Structure
š” Intermediate Non-Linear DS 60 min read
šÆ What is a Heap?
A Heap is a special tree-based data structure that satisfies the heap property. In a Max Heap, parent ℠children; in a Min Heap, parent ⤠children. It's a complete binary tree (all levels filled except possibly last, filled left to right). Used for priority queues, heap sort, and graph algorithms.
Max Heap: Min Heap:
100 1
/ \ / \
50 30 5 3
/ \ / / \ /
20 10 15 10 20 7
Array repr: [100,50,30,20,10,15]
For index i: left=2i+1, right=2i+2, parent=(i-1)/2
š» PHP Min Heap Implementation
<?php
class MinHeap {
private array $heap = [];
// Insert - O(log n)
public function insert(int $val): void {
$this->heap[] = $val;
$this->heapifyUp(count($this->heap) - 1);
}
private function heapifyUp(int $index): void {
while ($index > 0) {
$parent = intdiv($index - 1, 2);
if ($this->heap[$parent] <= $this->heap[$index]) break;
// Swap with parent
[$this->heap[$parent], $this->heap[$index]] =
[$this->heap[$index], $this->heap[$parent]];
$index = $parent;
}
}
// Extract Min - O(log n)
public function extractMin(): ?int {
if (empty($this->heap)) return null;
$min = $this->heap[0];
$last = array_pop($this->heap);
if (!empty($this->heap)) {
$this->heap[0] = $last;
$this->heapifyDown(0);
}
return $min;
}
private function heapifyDown(int $index): void {
$size = count($this->heap);
while (true) {
$smallest = $index;
$left = 2 * $index + 1;
$right = 2 * $index + 2;
if ($left < $size && $this->heap[$left] < $this->heap[$smallest])
$smallest = $left;
if ($right < $size && $this->heap[$right] < $this->heap[$smallest])
$smallest = $right;
if ($smallest === $index) break;
[$this->heap[$index], $this->heap[$smallest]] =
[$this->heap[$smallest], $this->heap[$index]];
$index = $smallest;
}
}
// Peek - O(1)
public function peek(): ?int {
return $this->heap[0] ?? null;
}
public function size(): int { return count($this->heap); }
public function isEmpty(): bool { return empty($this->heap); }
}
$heap = new MinHeap();
foreach ([5,3,8,1,9,2] as $v) $heap->insert($v);
while (!$heap->isEmpty()) {
echo $heap->extractMin() . ' '; // 1 2 3 5 8 9 (sorted!)
}
šļø Build Heap from Array - O(n)
// Heapify an array in-place (O(n) - Floyd's method)
function buildMinHeap(array &$arr): void {
$n = count($arr);
// Start from last non-leaf node
for ($i = intdiv($n, 2) - 1; $i >= 0; $i--) {
heapifyDownArray($arr, $n, $i);
}
}
function heapifyDownArray(array &$arr, int $n, int $i): void {
$smallest = $i; $left = 2*$i+1; $right = 2*$i+2;
if ($left < $n && $arr[$left] < $arr[$smallest]) $smallest = $left;
if ($right < $n && $arr[$right] < $arr[$smallest]) $smallest = $right;
if ($smallest !== $i) {
[$arr[$i], $arr[$smallest]] = [$arr[$smallest], $arr[$i]];
heapifyDownArray($arr, $n, $smallest);
}
}
// Heap Sort - O(n log n), O(1) space
function heapSort(array &$arr): void {
$n = count($arr);
buildMinHeap($arr);
for ($i = $n - 1; $i > 0; $i--) {
[$arr[0], $arr[$i]] = [$arr[$i], $arr[0]];
heapifyDownArray($arr, $i, 0);
}
// Reverse for ascending order
$arr = array_reverse($arr);
}
š PHP SplHeap
$heap = new SplMinHeap(); // or SplMaxHeap
$heap->insert(5); $heap->insert(3); $heap->insert(8);
foreach ($heap as $val) echo $val . ' '; // 3 5 8
echo $heap->top(); // 3 (minimum)
echo $heap->extract(); // 3 (removes it)
š Complexity
| Insert | O(log n) |
| Extract Min/Max | O(log n) |
| Peek | O(1) |
| Build Heap | O(n) |
| Heap Sort | O(n log n) |
š Key Applications
- Priority Queue: Task scheduling, Dijkstra's algorithm
- Heap Sort: O(n log n) in-place sorting
- Kth Largest/Smallest: Using min-heap of size k
- Median Finding: Two heaps (max + min)
- Merge K Sorted Lists: Min heap of list heads
š¼ Interview Questions
Use min-heap of size k. Iterate array, insert each element. If heap size > k, extractMin. After processing all, peek = kth largest. O(n log k).
Most nodes are near leaves where heapify is cheap. Analysis: Σ(h/2^h) converges to constant. So total work is O(n), not n à O(log n).