Heaps Building a heap
403. Does an Array Represent a Min Heap
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:
Example 1
Input: nums = [2, 5, 3, 9, 5, 8, 4]
trueExplanation: 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]
falseExplanation: 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]
falseExplanation: 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.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.