KatInterview

Build a Max-Heap In Place with Bottom-Up Sifting

Heaps, Sorting & SearchAuto-graded · 16 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaparraysift-down

Last 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:

  1. Let n be the length of the list. Visit indices from n // 2 - 1 down to 0 (the internal nodes, last to first).
  2. 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.
  3. 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.