oneby7

Heaps Building a heap

403. Does an Array Represent a Min Heap

Medium

You are given an array of integers nums. Return true if it represents a min heap, and false otherwise.

Read the array as a binary tree, level by level from left to right. nums[0] is the root, and the element at index i has its left child at index 2i + 1 and its right child at index 2i + 2, when those indexes are inside the array. The array is a min heap when every element is less than or equal to each of its children. A child equal to its parent is allowed.

This is the array of Example 1 drawn as that tree:

9552834
nums = [2,5,3,9,5,8,4]

Example 1

Input: nums = [2, 5, 3, 9, 5, 8, 4]

Output: true

Explanation: Each parent is at most its children: 2 sits above 5 and 3, 5 above 9 and 5, and 3 above 8 and 4. The array is not sorted, and it does not need to be.

Example 2

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

Output: false

Explanation: The 2 at index 2 has the children 3 at index 5 and 1 at index 6. Its right child is smaller than it, so the array is not a min heap. Every other parent is fine.

Example 3

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

Output: false

Explanation: The -3 at index 1 has only a left child, the -5 at index 3. -5 is smaller than -3.

Check your understanding

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

nums = [1, 5, 2, 6, 7, 3]

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.