Build a Max-Heap In Place with Bottom-Up Sifting
Heaps, Sorting & SearchAuto-graded · 16 test casesLast updated
Convert an integer list into a max-heap layout using the bottom-up sift-down procedure, matching an exact output array including tie-break behavior.
You are given a list of integers values. Treat it as a complete binary tree stored in a 0-indexed array: the node at index i has a left child at 2*i + 1 and a right child at 2*i + 2 (when those indices are within the list).
Rearrange the list so that it becomes a max-heap, meaning every node is greater than or equal to each of its children. Return the rearranged list.
Because many different arrangements are valid heaps, your result must match the one produced by the following exact procedure:
- Let
nbe the length of the list. Visit indices fromn // 2 - 1down to0(the internal nodes, last to first). - For each visited index, sift the value down:
- Find the largest among the current node and its existing children. A child replaces the current choice only if it is strictly greater than it. The left child is checked first, then the right child. So on a tie between the children, the left one wins, and a child equal to its parent never causes a swap.
- If the current node is already the largest, stop.
- Otherwise swap the current node with that child and continue sifting from the child's index.
- After all indices have been processed, return the list.
The input list may be modified in place; returning the same list is fine.
Constraints
0 <= len(values) <= 10^5- Each value is an integer that fits in a 32-bit signed range.
- Values may be negative or repeated.
- An empty list or a one-element list is returned unchanged.
- Your answer must follow the tie-break rules above exactly, since the output array is compared element by element.
Examples
Example 1
Input: build_max_heap([6, 15, 2, 4, 3, 8, 19])
Output: [19, 15, 8, 4, 3, 6, 2]
Hints
Hint 1
Work out which indices are leaves. Leaves are already valid one-element heaps, so only indices 0 to n // 2 - 1 need processing.
Hint 2
Process internal nodes from the highest index down to 0, so that both child subtrees are already heaps when you handle a node.
Hint 3
After swapping with a child, the moved value may still be smaller than its new children, so keep sifting down until no swap is needed or you reach a leaf. Use strict greater-than comparisons, checking left before right.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the heap in the array itself. Indices n // 2 to n - 1 are leaves, and a leaf is trivially a valid heap. So we only need to fix the internal nodes, going from the last internal node (n // 2 - 1) back to the root.
For each internal node we run a sift-down:
- Pick the largest among the node and its children, using strict
>and checking left before right. - If the node itself is the largest, stop.
- Otherwise swap with that child and repeat from the child's position.
Why it is correct
Invariant: when sift_down(i) begins, the subtrees rooted at 2i + 1 and 2i + 2 are already max-heaps. This holds because children have larger indices than their parent and we process indices in decreasing order.
The only possible violation is the value now at the top of the subtree. Swapping it with its larger child fixes the current level, and the larger child becomes the parent of the other child, so that side stays valid. The potential violation moves one level down, and it either gets resolved or reaches a leaf. After sift_down(i) the subtree at i is a heap, and after i = 0 the whole array is.
The strict comparisons make the result deterministic: ties between children go left, and equal parent/child pairs are never swapped.
Complexity
- Time: O(n). A node at height
hcosts O(h) and aboutn / 2^(h+1)nodes have heighth, so the sum is linear. - Space: O(1) extra, since the sift-down is iterative and works in place.
Reference solution
from typing import List
def build_max_heap(values: List[int]) -> List[int]:
n = len(values)
def sift_down(i: int) -> None:
while True:
largest = i
left = 2 * i + 1
right = left + 1
if left < n and values[left] > values[largest]:
largest = left
if right < n and values[right] > values[largest]:
largest = right
if largest == i:
return
values[i], values[largest] = values[largest], values[i]
i = largest
for i in range(n // 2 - 1, -1, -1):
sift_down(i)
return values