AlgoTales · Roadmap

Min heap

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A min heap is a tree-shaped pile where the smallest item is always on top and every parent is smaller than its children. You can see the smallest thing instantly and remove it quickly, without keeping the whole collection fully sorted.

Practical use cases

  • Web app: Next scheduled reminder. A reminders app holds thousands of future alerts, each with a send time. The worker only ever needs the soonest one. Keeping the alerts in a min heap means the next alert is always on top, so the worker checks one item per minute instead of scanning the whole table.
  • Web app: Cheapest quote on top. A travel site collects live price quotes from airlines and shows the cheapest first. Each new quote is placed into a min heap, and the top is always the lowest price. The page updates at once as quotes arrive, without sorting every time.
  • System: Timers, routes and merging streams. Operating systems keep timers in a min heap so the next one to fire is always at hand. Shortest-route finders such as Dijkstra use it to pick the closest unvisited place, and tools merging sorted streams use it to pick the smallest next value.

The story: The Cheapest Quote on Top

Aarav was planning his sister's wedding, and caterers kept sending quotes: ₹5,000, ₹3,000, ₹9,000, ₹2,000... Every time a new quote arrived, he sorted the whole pile again. By the fifth caterer his table was a mess and his chai had gone cold.

Grandpa Bhaskar chuckled. "Beta, why sort everything? You only ever need the cheapest one. Draw a family tree instead. Put the cheapest quote at the top as the grandfather. Under every quote, hang two others that are not cheaper than it."

Aarav tried it. Quote 2 on top; below it 5 and 3; below those 9, 6, 8 and 7. Every parent was cheaper than its children. "But 9 is on the left and 3 is on the right, and 3 is smaller!" he said. "Correct," smiled Grandpa. "Cousins never need to be sorted. Only the line from grandfather down must obey the rule."

That family tree is called a min heap. The smallest value is always at the very top, so the cheapest quote is one glance away, without sorting the whole pile.

How to spot this problem, and where you need it

You keep needing the smallest item (earliest time, lowest price, closest place) from a collection that keeps changing, and sorting everything each time is wasteful.

Signs you need it

  • You call min() or sort() on a growing list over and over just to read the first item.
  • The statement says "always get the smallest", "earliest deadline first", "cheapest next" or "priority queue".
  • Items come and go constantly, and you only care about the best one right now, not the complete order.

Where to use it in a project

  • Schedulers for emails, reminders and delayed jobs that fire the earliest item first.
  • Route-finding and price-comparison features that repeatedly pick the cheapest candidate.

The solution

Store the items in an array that is treated as a tree: the children of position i sit at 2i+1 and 2i+2. Keep the rule that each parent is not bigger than its children. The smallest is always at position 0. When you add or remove, move one item up or down until the rule holds again.

Payoff: Before: scanning 50,000 reminders every minute. After: read the top in one step and fix the heap in about 16 moves per change.

Explain it like I am 8

Imagine a pyramid of kids where the smallest kid always stands on top, and every kid is smaller than the two kids under them. You can always spot the smallest kid instantly, but the kids in the middle are not lined up in order.

How it works, step by step

  1. A min heap is a tree where every parent is smaller than or equal to its children.
  2. The tree is filled row by row from left to right, with no gaps. That keeps it short and tidy.
  3. The smallest value is always at the top (the root). Peeking at it costs one step.
  4. It is stored in a plain array: the children of spot i live at spots 2*i+1 and 2*i+2, and its parent at (i-1)/2 rounded down.
  5. Siblings and cousins are not sorted against each other. A heap is only "loosely ordered", and that is exactly why it is cheap to maintain.

The code in four languages

PHP

<?php
// A min heap lives in a plain array. Spot $i has children at 2*$i+1 and 2*$i+2.
function isMinHeap(array $a): bool {
    $n = count($a);
    for ($i = 0; $i < $n; $i++) {
        $left = 2 * $i + 1;
        $right = 2 * $i + 2;
        if ($left < $n && $a[$left] < $a[$i]) return false;     // a child is smaller than its parent
        if ($right < $n && $a[$right] < $a[$i]) return false;
    }
    return true;
}

$quotes = [2, 5, 3, 9, 6, 8, 7];
echo isMinHeap($quotes) ? 'valid' : 'broken', PHP_EOL;          // valid
echo 'Cheapest quote: ', $quotes[0], PHP_EOL;                    // one glance: 2
echo isMinHeap([2, 5, 3, 1, 6, 8, 7]) ? 'valid' : 'broken', PHP_EOL; // broken (1 is under 5)

JavaScript

// A min heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
function isMinHeap(a) {
  const n = a.length;
  for (let i = 0; i < n; i++) {
    const left = 2 * i + 1;
    const right = 2 * i + 2;
    if (left < n && a[left] < a[i]) return false;     // a child is smaller than its parent
    if (right < n && a[right] < a[i]) return false;
  }
  return true;
}

const quotes = [2, 5, 3, 9, 6, 8, 7];
console.log(isMinHeap(quotes) ? 'valid' : 'broken');          // valid
console.log('Cheapest quote: ' + quotes[0]);                  // one glance: 2
console.log(isMinHeap([2, 5, 3, 1, 6, 8, 7]) ? 'valid' : 'broken'); // broken (1 is under 5)

Java

public class Main {
    // A min heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
    static boolean isMinHeap(int[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int left = 2 * i + 1;
            int right = 2 * i + 2;
            if (left < n && a[left] < a[i]) return false;     // a child is smaller than its parent
            if (right < n && a[right] < a[i]) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int[] quotes = {2, 5, 3, 9, 6, 8, 7};
        System.out.println(isMinHeap(quotes) ? "valid" : "broken");          // valid
        System.out.println("Cheapest quote: " + quotes[0]);                  // one glance: 2
        System.out.println(isMinHeap(new int[]{2, 5, 3, 1, 6, 8, 7}) ? "valid" : "broken"); // broken (1 is under 5)
    }
}

Go

package main

import "fmt"

// A min heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
func isMinHeap(a []int) bool {
	n := len(a)
	for i := 0; i < n; i++ {
		left := 2*i + 1
		right := 2*i + 2
		if left < n && a[left] < a[i] { // a child is smaller than its parent
			return false
		}
		if right < n && a[right] < a[i] {
			return false
		}
	}
	return true
}

func verdict(ok bool) string {
	if ok {
		return "valid"
	}
	return "broken"
}

func main() {
	quotes := []int{2, 5, 3, 9, 6, 8, 7}
	fmt.Println(verdict(isMinHeap(quotes)))                     // valid
	fmt.Println("Cheapest quote:", quotes[0])                   // one glance: 2
	fmt.Println(verdict(isMinHeap([]int{2, 5, 3, 1, 6, 8, 7}))) // broken (1 is under 5)
}

Time: O(1) to peek the minimum · Extra space: O(n). Looking at the smallest value is instant; keeping the heap tidy after changes costs a few steps up or down one branch.

Watch out for

  • Thinking a heap is a sorted array. Only the top is guaranteed; the rest is just "parents beat children".
  • Believing the left child must be smaller than the right child. Siblings have no required order.
  • Leaving gaps. A heap fills each row from the left; a gap would break the array indexing.

Quick check

  1. In a min heap, where is the smallest value?
    • At the very bottom
    • At the top (the root)
    • In the middle
  2. Tree: 4 on top, 3 as its left child. Is it a valid min heap?
    • No, a child (3) is smaller than its parent (4)
    • Only if there is a right child
    • Yes
  3. Are the two children of the same parent sorted against each other?
    • No, there is no required order
    • Yes, left is smaller
    • Yes, right is smaller