oneby7

Heaps Building a heap

402. Build a Heap from an Array

Easy

You are given an integer array nums. Rearrange its elements so that the array becomes a min heap.

An array is a min heap when every element is less than or equal to its children. The children of index i are at indexes 2i + 1 and 2i + 2, when those indexes are inside the array. So the array is a binary tree written level by level: nums[0] is the root, nums[1] and nums[2] are its children, nums[3] and nums[4] are the children of nums[1], and so on. The smallest value always ends up at index 0.

64271839
Example 1's answer 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 min heaps, and any of them is a correct answer. The result shows a valid min heap of the given values when yours is one. Otherwise it names the first thing wrong, such as nums[3] = 9 is larger than its child nums[7] = 2 or the values changed: one copy of 4 is missing.

Aim for O(n) time and O(1) extra memory.

Example 1

Input: nums = [7, 2, 9, 4, 1, 8, 3, 6]

Output: [1,2,3,4,7,8,9,6]

Explanation: The elements with children are at indexes 0 to 3. 1 is no larger than its children 2 and 3, 2 is no larger than 4 and 7, 3 is no larger than 8 and 9, and 4 is no larger than 6. The sorted array [1,2,3,4,6,7,8,9] is also correct.

Example 2

Input: nums = [0, -5, 3, -5, 0, -1]

Output: [-5,-5,-1,0,0,3]

Explanation: A parent may equal its child: nums[0] and nums[1] are both -5. Both copies of -5 and both copies of 0 stay in the array.

Example 3

Input: nums = [8]

Output: [8]

Explanation: A single element has no children, so it is a min heap already and nothing moves.

Check your understanding

Work out the answer for this input before you write any code.

nums = [9, 3, 8, 2, 9, 1, 4]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

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.