oneby7

Heaps Building a heap

404. Convert a Min Heap to a Max Heap

Medium

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.

9562847
Example 1's input, a min heap, drawn as a tree

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]

Output: [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]

Output: [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]

Output: [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.

nums = [1, 2, 5, 3, 4]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums is a min heap.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.