Problem · Array
Insert into a Min-Heap
Learn this problemProblem statement
Given an array heap that represents a valid binary min-heap in level order and an integer value, insert value and return the resulting level-order array.
Append the value at the end, then repeatedly swap it with its parent while it is strictly smaller than that parent. Equal values do not swap.
Function
insertIntoMinHeap(heap: int[], value: int) → int[]Examples
Example 1
heap = [1,3,6,5,9,8]value = 2return = [1,3,2,5,9,8,6]After appending 2, swap it with its parent 6. Its new parent is 1, so the process stops.
Example 2
heap = []value = 4return = [4]The inserted value becomes the root of the previously empty heap.
Example 3
heap = [1,2,2,7]value = 2return = [1,2,2,7,2]The appended value equals its parent, so no swap occurs.
Constraints
0 <= heap.length <= 200000.heapis a valid binary min-heap.- Every stored value and
valueis a 32-bit signed integer.