CJCoding With Joseph
15free / daySign inCreate account

Remove the Minimum From a Min Heap

Complete removeMin() so it takes the smallest value out of the heap, returns it, and leaves the rest of the array a valid min heap.

Reminder: what a min heap is. A heap is a complete binary tree stored in an array, filled left to right with no gaps. In a min heap every parent is smaller than or equal to its children, so the smallest value always sits at index 0. A heap is NOT a binary search tree: it only promises the parent-child rule, so the two children of a node can be in either order. For the item at index i, the children are at 2 * i + 1 and 2 * i + 2.

array: [1, 3, 2, 5, 9, 8]

         1
       /   \
      3     2
     / \   /
    5   9 8

Taking the root out leaves a hole at the top. The standard fix is to move the LAST item into index 0, so the array still has no gaps, and then sift it down: compare it with its smaller child and swap while that child is smaller. Always pick the smaller of the two children, because it is the only one allowed to become the parent of the other.

Requirements: 1. Return -1 and change nothing when the heap is empty. 2. Save the value at index 0, move the last item into index 0, and make size one smaller. 3. Sift down from index 0: stop when the item has no children left, or when it is already less than or equal to its smaller child. 4. Return the value you saved. Use the helper methods the class already has, and do not change insert.

Do NOT write a main method.

Expected Output:

MinHeap: 1 3 2 5 9 8
1
MinHeap: 2 3 8 5 9
2
MinHeap: 3 5 8 9
4

= 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.