Implement a max-heap with decrease-key
Challenge · Write code · about 25 min
Run operations on a max-heap of items, each with an id and a key:
[0, id, key]inserts a new item.[1, id, key]lowers the key of a live item to the smallerkey.[2]removes the item with the largest key and reports itsid, or-1if the heap is empty.
Return the reported ids in order. All keys in one input are distinct. Decrease-key must run in O(log n).
Example 1
Input:
[[[0,0,4],[0,1,9],[0,2,7],[0,3,6],[1,1,5],[2],[2]]]
Output:
[2,3]
After the decrease, keys 7, 6, 5, 4 remain. Extracts report ids 2 and 3.
Example 2
Input:
[[[0,5,10],[0,6,20],[2],[2],[2]]]
Output:
[6,5,-1]
The third extract finds the heap empty.
Constraints
- 0 ≤ ops.length ≤ 10,000
- 0 ≤ id < 10,000 and 0 ≤ key ≤ 1,000,000
- Decrease-key only names a live id and a smaller key
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
- Implement push and pop Standard
- Spot the bug: sift down Standard