CJCoding With Joseph
15free / daySign inCreate account

Check Whether an Array Is a Min Heap

Complete isMinHeap(int[] values) so it returns true when the array, read as a heap, follows the min-heap rule, and false when any parent is bigger than one of its children.

Reminder: what makes an array a min heap. A heap is a complete binary tree kept in an array: index 0 is the root, and the node at index i has its left child at 2 * i + 1, its right child at 2 * i + 2 and its parent at (i - 1) / 2. The min-heap rule is only about parents and children: each parent must be smaller than or equal to both of its children. Unlike a BST, nothing compares a left child with its right sibling, so {1, 5, 2} is a perfectly good min heap.

values:  2  4  3  9  6  1

         2                 index 5 holds 1, but its
       /   \               parent (index 2) holds 3,
      4     3              so this array is NOT
     / \   /               a min heap
    9   6 1

Checking means looking at every parent-child pair once. Nodes near the end of the array have one child or none, so a child index can land past the end and must be compared with values.length before you read it.

Requirements: 1. Return false as soon as some existing child is smaller than its parent. 2. Return true when every pair passes, which includes an empty array and a single value. 3. Equal values are allowed: a parent may equal its child. 4. Use the provided leftChild(int i) and rightChild(int i) helpers, and do not change the array.

Do NOT write a main method.

Expected Output:

true
true
false
false

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsHeaps
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.