Skip to the code
cf.
+25 XP

#201 Heap Sort After K Extractions

medium

A debugging panel pauses heap sort partway through. Heap sort first builds a max-heap bottom-up (as in the previous problem's rules: sift down from the last parent to the root, swapping with the strictly bigger child, left child on ties). Then each extraction swaps the root with the last item of the heap and sifts the new root down within the smaller heap.

Write afterExtractions(nums, k) that returns the array after building the heap and then doing k extractions.

Example 1

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

The heap is [10, 5, 3, 4, 1]. Swap 10 to the end, then sift 1 down past 5 and 4.

Example 2

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

After n - 1 extractions the array is fully sorted.

Constraints

  • 0 <= nums.length <= 10000
  • 0 <= k <= max(0, nums.length - 1)
  • -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).