All topics
81

Heapify and pop: build a heap all at once, then remove the min

Tier 1Locked

Where it runs

1. The problem

In step 80 you grew a heap one push at a time, and each new value climbed up (sift up). Now you already have a whole array of numbers, and you want it to become a heap in one go. You also want to keep taking the smallest value out.

You could push the numbers into an empty heap one by one. That works, but it costs O(n log n): n pushes, and each one can climb up to log n levels. There is a faster way: reorder the array you already have, in place, in O(n).

Once you have a heap, you need the other half too: take the smallest value out and leave a valid heap behind, so it can hand you the next smallest. Both jobs use one new move, the mirror image of sift up: sift down.

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

Simulation problems that take the biggest or smallest item many times and put a changed one back. Heapify the input in O(n), then each pop and push costs O(log n).

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