Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-077

Heap Replace Root

Problem

Replace the root of a min-heap with a new value and restore the heap property.

heap is a valid min-heap list. Overwrite the root with value, then sift it down by swapping with its smaller child until both children are greater than or equal to it. An empty heap becomes [value].

Return the updated heap as a new list.

Hint

This is the sift-down used when popping; the same routine handles an empty heap.

Test cases

case 1
in: [[1,3,2,7,5],4]
expected: [2,3,4,7,5]
case 2
in: [[2,5],9]
expected: [5,9]
case 3
in: [[],7]
expected: [7]
case 4
in: [[1,2,3],0]
expected: [0,2,3]
Starter codePython
def heap_replace(heap, value):
    # Your code here
    pass

4 test cases · run your code against them in the editor