Heapify Time Complexity

In short: Building a heap with bottom-up heapify (sifting nodes down, starting from the bottom of the tree) runs in O(n), not O(n log n). Half the nodes are leaves that never move, and only the few nodes near the root can move far, so the total work sums to O(n).

In the simpler analysis, we said that each of the n elements in the tree might have to move down times, since the tree had height .

That's true, but it's a bit of an overestimate. For instance, all of the leaf nodes at the bottom of the tree won't have to move down at all. And the parents of those nodes will only move down once. In fact, there's only one node that might move down times: the root node.

Since binary heaps are based on complete binary trees, there will be n/2 nodes in the bottom level, n/4 nodes in the second-to-last level, etc. Each time we go up a level we cut the number of nodes in half.

With that in mind, let's look at how many downward moves it'll take to transform the tree into a heap. We'll say the tree height is h and level 1 is the root.

Level Nodes Moves Work
h \frac{n}{2} 0 0
h - 1 \frac{n}{4} 1 \frac{n}{4}
h - 2 \frac{n}{8} 2 2 * \frac{n}{8}
h - 3 \frac{n}{16} 3 3 * \frac{n}{16}
\vdots \vdots \vdots \vdots
1 1 h h

Adding this all up, we've got:

\frac{n}{4} + 2 * \frac{n}{8} + 3 * \frac{n}{16} + \ldots

Alternatively, this can be expressed as a summation:

\sum i * \frac{n}{2^{i + 1}}

It turns out that this sequence converges to n/2. That's .

Our heapify algorithm works from the bottom of the tree upwards. What if we worked from the top of the tree downwards—having each child "bubble up" to replace its parent?

It turns out to be more expensive—. Can you figure out why? (Hint: how many leaf nodes do we have, and how many times might each one move?)

Frequently Asked Questions

What is the time complexity of heapify?

Building a heap from n items with bottom-up heapify takes O(n) time. Sifting a single node down, which is sometimes also called heapify, takes O(log n).

Why is building a heap O(n) and not O(n log n)?

Most nodes are near the bottom: about n/2 leaves move 0 levels, n/4 nodes move at most 1, n/8 at most 2, and so on. That series adds up to O(n).

Is inserting items one at a time just as fast?

No. Inserting n items one by one with sift-up is O(n log n) in the worst case, which is why bottom-up heapify is used when all the items are available up front.

Last updated: October 21, 2026

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .