What is a heap?
A heap is a priority queue shaped like a complete binary tree and stored flat in an array. You do not keep every value sorted — you only promise that the best value sits at the root. Reading that best value is instant; putting a new value in the right place costs a short climb or slide along parent–child links.
- Priority
- The “best” value at the root — smallest for a min-heap, largest for a max-heap
- Parent / child indexes
- For index
i: parentMath.floor((i - 1) / 2), left2 * i + 1, right2 * i + 2 - Min vs max
- Same tree shape; only the compare direction flips. Interviews usually ask for a min-heap unless they say otherwise.
See it as a tree and an array
Draw the heap as a tree and you see parents watching their children. Lay the same values left-to-right in an array and you see why the formulas work — level order fills the row without gaps.
Watch a parent light up with both children. The array cells with the same indexes flash together. Same structure, two views.
Parent at i · children at 2i+1 and 2i+2. No holes until the last level.
Types of heaps
Most interview heaps are binary heaps. You pick the order — min or max — and keep the tree complete so the array stays packed from the left.
Exotic cousins (binomial, Fibonacci) show up in textbooks. Day-to-day coding interviews almost always mean “array-backed binary heap.”
Order answers “what is best?” Shape answers “how do we store it?”
How it is stored in memory
TypeScript keeps a reference on the stack and the values in one contiguous array on the heap. There are no left/right pointers — parent and child are pure index math on that array.
Tap Next to walk from “empty binding” to “read a child by formula.”
Start here. Each step highlights the TypeScript below.
Operations
Four moves cover almost every heap interview: push with sift-up, peek the root, extract with sift-down, and heapify an unordered list. Tap Next on each demo — watch the value bubble through swaps. For copy-paste helpers, open the Functions tab.
Insert + sift-up
Drop the new value at the next open slot (the end of the array). If it outranks its parent, swap and keep climbing until the invariant holds — or you hit the root.
Press Next to append 1 at the end.
Peek
Read the root. You do not walk the tree — index 0 is always the current best.
Nothing moves.
Press Next to peek at heap[0].
Extract + sift-down
Save the root, move the last value into the hole, then slide that value down — always swapping with the better child — until every parent beats its kids again.
Press Next to pull the root and sift down.
Heapify
Start from the last parent and sift each one down. Bottom-up heapify builds a valid heap in linear time — cheaper than pushing every value one by one.
[9, 5, 3, 2, 7]Press Next to sift parents from the bottom up.