Heaps Building a heap
400. Implement Min Heap
Build a min heap of integers on an array. A min heap gives back its smallest value first, whatever order the
values went in. Write a class MinHeap with four methods:
push(x)addsxto the heap.pop()removes the smallest value and returns it.peek()returns the smallest value without removing it.size()returns how many values the heap holds.
push and pop must run in O(log n) time, and peek and size in O(1), where n is the number of values in
the heap.
Keep the values in an array (a list or a vector) and arrange them yourself. Your language's priority queue
(priority_queue, PriorityQueue, heapq, BinaryHeap) would pass the tests too, because the judge only
sees what your methods return. Building the heap yourself is the exercise.
Your class is tested by replaying a list of calls on a new, empty MinHeap. ops[i] names the i-th call:
"push", "pop", "peek" or "size". The pushes take their values from values in order, so the first push
pushes values[0], the second pushes values[1], and so on. The answer is the list of every value that pop,
peek and size return, in the order they are called.
In C# and Go the methods are Push, Pop, Peek and Size. Go creates the heap with Constructor(), and
Rust with MinHeap::new(). The names in ops are the same in every language.
Example 1
Input: ops = ["push",
"push",
"push",
"push",
"peek",
"pop",
"pop",
"size",
"peek"]
values = [5, 2, 8, 1]
[1,1,2,2,5]Explanation: The smallest value comes out first, whatever the order of the pushes. peek and the first pop both give
1, and the second pop gives 2. Only 5 and 8 are left, so size is 2 and peek is 5.
Example 2
Input: ops = ["push",
"push",
"push",
"pop",
"peek",
"size",
"pop",
"pop",
"size"]
values = [-3, 0, -3]
[-3,-3,2,-3,0,0]Explanation: -3 is pushed twice, and each copy is a value of its own, so the first pop removes only one of them. After
the last pop the heap is empty, and size returns 0.
Example 3
Input: ops = ["push",
"size",
"push",
"pop",
"push",
"peek",
"pop",
"pop"]
values = [1000000000, -1000000000, 7]
[1,-1000000000,7,7,1000000000]Explanation: 7 is pushed after a pop, and it joins the one value left, 1000000000. It is the smaller of the two, so it
comes out first.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ ops.length ≤ 105- Each
ops[i]is"push","pop","peek"or"size". values.lengthequals the number of"push"calls inops.-109 ≤ values[i] ≤ 109popandpeekare only called when the heap is not empty.
Clarifying questions
What you would ask an interviewer before writing any code.