Skip to the code
cf.
+10 XP

#377 Is This Array a Valid Heap?

easy

A task scheduler saves its priority queue to disk as a plain array in min-heap order. Before loading it back, you want to check that the array really is a min-heap.

In a min-heap stored in an array, the children of index i are at 2 * i + 1 and 2 * i + 2 (when those indexes exist), and every parent must be less than or equal to its children. Write isMinHeap(values) that returns true if values follows that rule everywhere, and false otherwise. An empty array is a valid heap.

Example 1

Input: values = [1,3,2,7,4]
Output: true

1 is at most 3 and 2; 3 is at most its children 7 and 4.

Example 2

Input: values = [1,3,2,1]
Output: false

Index 3 is a child of index 1, and 1 is smaller than its parent 3.

Constraints

  • 0 <= values.length <= 10^5
  • -10^9 <= values[i] <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).