Heaps / Priority Queue

A heap gives you the smallest (or largest) item in O(1) and adds or removes items in O(log n). It is the tool for top-K, merging sorted streams, running medians and scheduling.

Overview

A heap is a binary tree stored in a plain array. It keeps one rule, the heap property: in a min-heap every parent is less than or equal to its children, so the smallest item is always at the root. A max-heap flips the rule, so the largest item is at the root.

A heap is only partly ordered. It knows the minimum, but the array is not sorted, and finding any other value means scanning all of it. That partial order is cheap to keep up, and it drives top K, running medians and merging sorted lists.

Each section below follows the same shape: the rule first, then the rule on a small heap, then the trap to avoid.

What a heap is

The rule: the tree is always complete: every level is full except the last, which fills from the left. That shape is why the height stays about log2(n) and why no pointers are needed.

The same heap is the array [1, 3, 5, 7, 8, 9, 10, 12, 15], read level by level, left to right. Parent and child positions come from arithmetic on the index (0-based).

  • Parent of index i: (i - 1) // 2.
  • Left child: 2i + 1.
  • Right child: 2i + 2.

Take i = 1, the value 3: its parent is index 0 (value 1), its left child is index 3 (value 7), and its right child is index 4 (value 8). Check them against the tree.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio