Heaps Building a heap
404. Convert a Min Heap to a Max Heap
You are given an integer array nums that is a min heap. Rearrange its elements so that the array becomes
a max heap.
An array is a heap when we read it as a binary tree, level by level: nums[0] is the root, and the children of
nums[i] are nums[2i + 1] and nums[2i + 2], when those exist. In a min heap every parent is less than or
equal to each of its children. In a max heap every parent is greater than or equal to each of its children.
Change nums itself. The function returns nothing. The array must keep exactly the values it was given, each as many times as before.
Many arrangements are max heaps, and any of them is a correct answer. The result shows
a valid max heap of the given values when yours is one. Otherwise it names the first thing wrong, such as
nums[1] = 5 is smaller than its child nums[3] = 9 or the values changed: one copy of 4 is missing.
Aim for O(n) time and O(1) extra memory.
Example 1
Input: nums = [2, 5, 4, 9, 6, 8, 7]
[9,6,8,5,2,4,7]Explanation: 9 is at least its children 6 and 8, 6 is at least 5 and 2, and 8 is at least 4 and 7. [9,8,7,6,5,4,2]
is also correct.
Example 2
Input: nums = [-3, -3, 0, -1, 4]
[4,-1,0,-3,-3]Explanation: 4 is at least -1 and 0, and -1 is at least both -3s. A parent may equal its child, so the two -3s could also sit one above the other.
Example 3
Input: nums = [1, 3, 9, 8]
[9,8,1,3]Explanation: Reversing the input gives [8,9,3,1], which is not a max heap: 9 sits below 8.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109numsis a min heap.
Clarifying questions
What you would ask an interviewer before writing any code.