Where it runs
1. The problem
In step 78 you walked up a tree to find where two branches meet. A heap is a tree too. It keeps just enough order that you can always take the smallest number at once.
Here is the task. You have a set of numbers, and it keeps changing. Over and over, you need the smallest number in it right now. New numbers keep arriving while you work.
You could keep the whole set sorted. That is extra work: every insert has to shift items so the new value lands in its exact place. You only need one thing to stay true: the smallest number always sits where you can read it in one step.
A heap does exactly that. It needs no tree nodes and no links between them: it lives in a plain array (a numbered list of boxes). In this lesson you build its two parts: how the tree is laid out in the array, and how to insert a new number.
This step is part of the paid track
The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.
Create a free accountSee what is includedOn LeetCode
LeetCode rarely asks for a heap push on its own, so these problems train the other half of the lesson, numbering a tree like an array. The parent of i is (i minus 1) >> 1 and the children are 2i + 1 and 2i + 2, which turns questions about tree shape into arithmetic. The heap problems start in lesson 81.
Number the nodes the way a heap numbers its slots, and the tree is complete when the largest number is the node count minus 1.
Give each node its heap number and measure each level as last minus first plus 1, renumbering from 0 on each level so the numbers stay small.
With heap numbering the parent of a label is label >> 1, and the zigzag only mirrors the label inside its level.