Problems/701. Min Heap Mechanics

701. Min Heap Mechanics

MediumHeapPriority QueueSift UpSift Down

A Min Heap is a specialized complete binary tree structure designed for efficient priority operations. In a min heap, every parent node maintains a value less than or equal to its children's values, meaning the smallest item is always at the root.

This mechanic visualizes the two primary mutations:

  1. Insertion (Sift-Up): Placing a new value at the very end of the tree and bubbling it upwards until it respects the parent-child ordering.
  2. Extraction (Sift-Down): Removing the root minimum, replacing it with the last element in the tree, and sinking that element down by repeatedly swapping it with its smallest child to restore the heap property.
Example 1
Input: heap = [3, 8, 10, 15, 20, 25], insert = 2
Output: heap = [2, 8, 3, 15, 20, 25, 10]
The value 2 is appended at index 6, then sifted up by swapping with its parent 10, and then parent 3, becoming the new root.
Example 2
Input: heap = [2, 8, 3, 15, 20, 25, 10], extractMin()
Output: heap = [3, 8, 10, 15, 20, 25], min = 2
The root 2 is swapped with the last element 10, then popped. 10 is sifted down by swapping with its smaller child 3, restoring the heap.
Example 3
Input: array = [20, 8, 25, 15, 3, 10], heapify()
Output: heap = [3, 8, 10, 15, 20, 25]
Running sift-down starting from the last parent index down to index 0 reorganizes the unsorted array into a valid min-heap structure.
Visualizer

Visualizer will appear here