Skip to content

Data Structures

Min-Heap

Insert: O(log n), because an item only ever travels up one branch of the tree · Remove the smallest: O(log n) · Peek at the smallest: O(1), instant.

The idea, in plain English

A min-heap is like a hospital waiting room organized by urgency. The most critical patient is always easiest to reach, at the front. Everyone else is only loosely arranged, not fully sorted.

How it works

  1. 1Insert: put the new item at the end. Let it 'bubble up' past any bigger parent, until it lands in a valid spot.
  2. 2Peek: the smallest item always sits at the top. You don't need to search for it.
  3. 3Remove the smallest: swap it with the last item, then remove it. Let that last item 'bubble down' past smaller children.

When you'd use it

Use a min-heap for task schedulers that must run the most urgent job next, for finding the smallest or largest few items in a big pile, or for Dijkstra's shortest-path algorithm.

Common beginner mistakes

  • Don't think a heap is fully sorted. It only guarantees the smallest item is on top. The other items are not in order.
  • Don't build it as a tree of linked nodes. A heap is usually just a plain array. Simple math finds each parent and child by index.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Smallest: 1
Pop: 1
Pop: 2
Remaining: 4

Note: Python's built-in heapq module is the standard tool for a heap. It manages a plain list for you. The JavaScript version here writes the same bubble-up and bubble-down logic by hand, so you can see how a heap really works underneath.

See it in motion

Watch it bubbleMin-heapInsert: O(log n), because an item only ever travels up one branch of the tree · Remove the smallest: O(log n) · Peek at the smallest: O(1), instant.
Backing array
empty

Empty heap. Insert values — each bubbles up.

0
Size
—
Peek (min)
0
Swaps
0.0s
Time
ComparingSwappingMin / placedResting

Not sure this is the right topic? See the learning paths → or where this leads →