Skip to content

Heapify a List in Place

Easy#heapify#sift-down~15 min

The mission

Problem

Rearrange a list of numbers into a min-heap in place, without the heapq module, and return it. In a min-heap stored in a list, the children of index i are at 2i + 1 and 2i + 2, and every parent is at most each of its children. Use the bottom-up method: sift each parent down, starting from the last parent and moving towards the root, so the whole build runs in O(n).

Examples

Input:  nums = [5, 3, 8, 1, 2]
Output: [1, 2, 8, 3, 5]
Why:    3 swaps with its child 1, then 5 sinks from the root past 1 and 2
Input:  nums = [9, 8, 7, 6, 5, 4, 3, 2, 1]
Output: [1, 2, 3, 6, 5, 4, 7, 8, 9]
Input:  nums = [42]
Output: [42]
Why:    edge case, one element is already a heap

Hints

0 / 3

Target time
O(n)
Target space
O(1)

Stuck on the idea rather than the code? Heapify and Sift covers it.

Python 3Ctrl+Enter runs