Skip to the code
cf.
+25 XP

#200 Heapify the Task List

medium

A task scheduler stores urgency scores in an array that it treats as a binary tree: the children of index i are 2i + 1 and 2i + 2. Before it can serve the most urgent task first, it must turn the array into a max-heap, where every parent is at least as big as its children.

Build the heap bottom-up, exactly like heap sort's first phase: for i from Math.floor(n / 2) - 1 down to 0, sift nums[i] down. Sifting compares the item with its children and, if a child is strictly bigger, swaps it with the bigger child (the left one if both children are equal) and continues from there.

Write buildMaxHeap(nums) that returns the array after building the heap.

Example 1

Input: nums = [4,10,3,5,1]
Output: [10,5,3,4,1]

10 stays above 5 and 1; then 4 sinks below 10 and then below 5.

Example 2

Input: nums = [1,2,3]
Output: [3,2,1]

The root 1 swaps with its bigger child, 3.

Constraints

  • 0 <= nums.length <= 10000
  • -10^6 <= nums[i] <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).