Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-021

Heap Push and Pop

Problem

Simulate a min-heap (priority queue) supporting push, pop, and peek.

operations contains "push", "pop", or "peek"; values provides the pushed value (ignored otherwise). push records None, while pop and peek return the smallest element or None when the heap is empty.

Implement push with sift-up, and pop by moving the last element to the root and sifting it down.

Hint

Pop swaps the root with the last element, shrinks the list, then sifts the new root down.

Test cases

case 1
in: [["push","push","push","pop","peek"],[3,1,2,0,0]]
expected: [null,null,null,1,2]
case 2
in: [["pop","push","pop","pop"],[0,5,0,0]]
expected: [null,null,5,null]
case 3
in: [["push","push","push","pop","pop","pop"],[2,3,1,0,0,0]]
expected: [null,null,null,1,2,3]
case 4
in: [["peek"],[0]]
expected: [null]
Starter codePython
def heap_push_pop(operations, values):
    # Your code here
    pass

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