LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

How do replaceKey(e, k) and remove(e) work in a heap-based adaptable priority queue, and why do they take $O(\log n)$?

The location-aware entry leads straight to e's node in $O(1)$. replaceKey changes the key there and then runs upheap if the key got smaller or downheap if it got larger. remove swaps e with the last node, deletes the last node and repairs the moved entry the same way. Only the up- or downheap costs time, and that is $O(\log n)$.

Three heaps of entries: entry g with key 8 at index 4 gets key 1, swaps up to index 2 and then to the root, updating stored indices

* replaceKey(g, 1): the stored index finds g at once; each upheap swap also updates the two entries' stored indices. *

replaceKey(e, k): after changing the key, only one parent–child relationship around e can be wrong:

  • If k is smaller than before, e may now be smaller than its parent: upheap from e's position.
  • If k is larger, e may now be larger than one of its children: downheap from e's position.

Comparing k with the parent's key decides the direction; at most one of the two moves anything.

remove(e): e's node usually is not the last node, and removing it directly would leave a hole. So, as in removeMin, the last node's entry is moved into e's position, the last node is deleted, and the moved entry is repaired with up- or downheap. Unlike removeMin, the moved entry may need to go up, because it came from a different branch of the tree.

Example: in a heap holding 2 at the root, 4 and 6 below it, and 8, 5, 9 at the bottom, replaceKey turning 8 into 1 upheaps 1 past 4 and 2 to the root in two swaps. Each swap also updates the two entries' stored indices.

Finding the node is $O(1)$ and the repair is bounded by the height, so both operations are $O(\log n)$.

Go deeper:

  • doc Binary heap: delete — removing an arbitrary element by swapping in the last one and sifting up or down.

From Quiz: ADS / Priority Queues and Heaps | Updated: Nov 26, 2026