Implement push and pop
Standard · Write code · about 15 min
Build a min-heap in an array and run a list of operations on it. A value x ≥ 0 means push x. The value -1 means pop the smallest value and report it, or report -1 when the heap is empty.
Return the reported values in order. Write sift up and sift down yourself; do not sort.
Example 1
Input:
[[5,3,8,-1,-1]]
Output:
[3,5]
After three pushes the root is 3. Two pops return 3, then 5.
Example 2
Input:
[[-1,4,-1,-1]]
Output:
[-1,4,-1]
Popping an empty heap reports -1.
Constraints
- 0 ≤ ops.length ≤ 10,000
- Each op is -1 or a value from 0 to 100,000
Learn the idea first: Binary heaps: array layout, sift up, sift down, a visual lesson.
More Binary heaps: array layout, sift up, sift down problems
- Parent and child indices Warm-up
- Which array is a min-heap? Warm-up
- Insert into a heap Warm-up
- Is this array a min-heap? Warm-up
- Extract the minimum Standard
- Spot the bug: sift down Standard
- Implement a max-heap with decrease-key Challenge