Skip to content
BytePatterns

Min-Heap Array Check

EasyHeaps#heap#array-as-tree~15m

Problem

A list of numbers can be read as a binary tree: the value at index i has its children at indexes 2i + 1 and 2i + 2, when those exist. Decide whether the list already satisfies the min-heap rule, meaning no value is larger than either of its children. Return True if it does and False otherwise. An empty list or a single value counts as a valid heap.

Examples

Input:  values = [1, 3, 2, 7, 4]
Output: True
Why:    1 sits above 3 and 2, and 3 sits above 7 and 4
Input:  values = [2, 1, 3]
Output: False
Why:    the root 2 is larger than its left child 1
Input:  values = [5, 5, 5]
Output: True
Why:    edge case, equal values never break the rule

Hints

0 / 3

Stuck on the idea rather than the code? Heapify and Sift covers it.