All topics
80

A heap: a tree folded into an array

Tier 1Locked

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 included

On 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.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy