AlgoFrames

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 smaller key.
  • [2] removes the item with the largest key and reports its id, or -1 if 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