Delete
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Deleting an item from the middle of a heap works by replacing it with the last item, then moving that item up or down until the heap rule holds. Nothing has to shift, so cancelling a queued job stays cheap.
Practical use cases
- Web app: Cancelling a scheduled email campaign. A marketer cancels one campaign out of 5,000 waiting in the send queue. The app removes it by dropping the last campaign into its place and repairing the short path. The queue is correct again without pausing sends or rebuilding. Other campaigns carry on exactly as before.
- Web app: Dropping a cancelled food order. A customer cancels a pending order. The dispatcher heap must forget it so no rider is sent for nothing. The last order takes its slot and is corrected in a few swaps, so the queue stays accurate and nothing else has to move.
- System: Cache eviction and graph algorithms. Caches that evict the least valuable entry, and graph algorithms that lower or drop a candidate, remove or change an item in the middle of a heap. They do it with this same last-item swap and repair. It keeps the structure valid without ever shifting the whole array.
The story: The Cancelled Booking
Aarav was happy with his caterer pile arranged as a min heap, until one afternoon a caterer from the middle of the tree called to cancel. Not the cheapest one, just a random one. Aarav scratched his head. "If I remove him, there is a hole in the family tree. What now?"
Mira had a clever idea. "A hole in the middle is a problem, but a hole at the end is not. Take the very last quote and move it into the hole. The tree is full again!" Aarav said, "But the one I moved may be too big or too small for its new seat."
"Then just fix it," said Mira. "If it is smaller than its new parent, it climbs. If it is bigger than a child, it sinks. Only one of those can be true, and it only travels along one branch." In the first example, 9 sank one level. In the second, 4 climbed one level. Both were done in a flash.
That is delete in a heap: swap the doomed item with the last one, shrink the heap by one, then sift up or down. Deleting the top is just a special case of this, which has its own lesson next.
How to spot this problem, and where you need it
You must remove a specific item that is not at the top of a priority queue, such as a cancelled job, without disturbing the order of everything else.
Signs you need it
- Users can cancel or edit queued items, and your code scans the whole queue to find and remove them.
- Removing from the middle forces a complete rebuild or sort of the queue.
- The task asks to "delete an arbitrary element from a heap".
Where to use it in a project
- Job, email and notification queues where a queued item can be cancelled.
- Cache and scheduler code that must drop an entry before its turn.
The solution
Find the item's position, which a lookup table of positions makes instant. Move the last item of the array into that position and shrink the array by one. Then compare the moved item with its parent and children: swap it up if it beats its parent, or down if a child beats it. One of the two directions will be needed, never both.
Payoff: Before: rebuilding a queue of 5,000 items per cancel. After: one move plus about 12 swaps in the worst case.
Explain it like I am 8
In a pyramid of kids, one kid in the middle goes home. Instead of shuffling everyone, the kid from the very last spot walks over to fill the gap. Then they check: "Am I smaller than the one above me? Climb. Am I bigger than one below me? Sink."
How it works, step by step
- Find the item. (Finding it by value means scanning the array, which is slow, so real systems remember its spot.)
- Take the last item of the heap and move it into the hole. Shrink the heap by one.
- If the moved item is smaller than its parent (min heap), sift up.
- Otherwise sift down: swap with its smaller child while a child is smaller.
- If you deleted the last item itself, there is nothing to fix.
The code in four languages
PHP
<?php
function siftUp(array &$a, int $i): int { // climb while smaller than the parent
while ($i > 0) {
$p = intdiv($i - 1, 2);
if ($a[$i] >= $a[$p]) break;
[$a[$i], $a[$p]] = [$a[$p], $a[$i]];
$i = $p;
}
return $i;
}
function siftDown(array &$a, int $i): void { // sink while a child is smaller
$n = count($a);
while (true) {
$l = 2 * $i + 1; $r = $l + 1; $s = $i;
if ($l < $n && $a[$l] < $a[$s]) $s = $l;
if ($r < $n && $a[$r] < $a[$s]) $s = $r;
if ($s === $i) return;
[$a[$i], $a[$s]] = [$a[$s], $a[$i]];
$i = $s;
}
}
function deleteAt(array &$a, int $i): void {
$last = array_pop($a); // remove the last item
if ($i === count($a)) return; // we deleted the last item itself
$a[$i] = $last; // plug the hole
$i = siftUp($a, $i); // climb if it is too small...
siftDown($a, $i); // ...otherwise sink if it is too big
}
$heap = [1, 4, 2, 6, 5, 3, 8, 7, 9];
deleteAt($heap, array_search(4, $heap, true)); // finding by value is a slow scan
echo implode(' ', $heap), PHP_EOL; // 1 5 2 6 9 3 8 7
$heap = [1, 10, 2, 11, 12, 3, 4];
deleteAt($heap, array_search(11, $heap, true));
echo implode(' ', $heap), PHP_EOL; // 1 4 2 10 12 3JavaScript
function siftUp(a, i) { // climb while smaller than the parent
while (i > 0) {
const p = (i - 1) >> 1;
if (a[i] >= a[p]) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
return i;
}
function siftDown(a, i) { // sink while a child is smaller
const n = a.length;
for (;;) {
const l = 2 * i + 1, r = l + 1; let s = i;
if (l < n && a[l] < a[s]) s = l;
if (r < n && a[r] < a[s]) s = r;
if (s === i) return;
[a[i], a[s]] = [a[s], a[i]];
i = s;
}
}
function deleteAt(a, i) {
const last = a.pop(); // remove the last item
if (i === a.length) return; // we deleted the last item itself
a[i] = last; // plug the hole
i = siftUp(a, i); // climb if it is too small...
siftDown(a, i); // ...otherwise sink if it is too big
}
let heap = [1, 4, 2, 6, 5, 3, 8, 7, 9];
deleteAt(heap, heap.indexOf(4)); // finding by value is a slow scan
console.log(heap.join(' ')); // 1 5 2 6 9 3 8 7
heap = [1, 10, 2, 11, 12, 3, 4];
deleteAt(heap, heap.indexOf(11));
console.log(heap.join(' ')); // 1 4 2 10 12 3Java
import java.util.*;
public class Main {
static int siftUp(List<Integer> a, int i) { // climb while smaller than the parent
while (i > 0) {
int p = (i - 1) / 2;
if (a.get(i) >= a.get(p)) break;
Collections.swap(a, i, p);
i = p;
}
return i;
}
static void siftDown(List<Integer> a, int i) { // sink while a child is smaller
int n = a.size();
while (true) {
int l = 2 * i + 1, r = l + 1, s = i;
if (l < n && a.get(l) < a.get(s)) s = l;
if (r < n && a.get(r) < a.get(s)) s = r;
if (s == i) return;
Collections.swap(a, i, s);
i = s;
}
}
static void deleteAt(List<Integer> a, int i) {
int last = a.remove(a.size() - 1); // remove the last item
if (i == a.size()) return; // we deleted the last item itself
a.set(i, last); // plug the hole
i = siftUp(a, i); // climb if it is too small...
siftDown(a, i); // ...otherwise sink if it is too big
}
public static void main(String[] args) {
List<Integer> heap = new ArrayList<>(List.of(1, 4, 2, 6, 5, 3, 8, 7, 9));
deleteAt(heap, heap.indexOf(4)); // finding by value is a slow scan
System.out.println(heap); // [1, 5, 2, 6, 9, 3, 8, 7]
heap = new ArrayList<>(List.of(1, 10, 2, 11, 12, 3, 4));
deleteAt(heap, heap.indexOf(11));
System.out.println(heap); // [1, 4, 2, 10, 12, 3]
}
}Go
package main
import "fmt"
// siftUp climbs while smaller than the parent and returns the final spot.
func siftUp(a []int, i int) int {
for i > 0 {
p := (i - 1) / 2
if a[i] >= a[p] {
break
}
a[i], a[p] = a[p], a[i]
i = p
}
return i
}
// siftDown sinks while a child is smaller.
func siftDown(a []int, i int) {
n := len(a)
for {
l, r, s := 2*i+1, 2*i+2, i
if l < n && a[l] < a[s] {
s = l
}
if r < n && a[r] < a[s] {
s = r
}
if s == i {
return
}
a[i], a[s] = a[s], a[i]
i = s
}
}
func deleteAt(a []int, i int) []int {
last := a[len(a)-1]
a = a[:len(a)-1] // remove the last item
if i == len(a) { // we deleted the last item itself
return a
}
a[i] = last // plug the hole
i = siftUp(a, i) // climb if it is too small...
siftDown(a, i) // ...otherwise sink if it is too big
return a
}
func indexOf(a []int, x int) int { // finding by value is a slow scan
for i, v := range a {
if v == x {
return i
}
}
return -1
}
func main() {
heap := []int{1, 4, 2, 6, 5, 3, 8, 7, 9}
heap = deleteAt(heap, indexOf(heap, 4))
fmt.Println(heap) // [1 5 2 6 9 3 8 7]
heap = []int{1, 10, 2, 11, 12, 3, 4}
heap = deleteAt(heap, indexOf(heap, 11))
fmt.Println(heap) // [1 4 2 10 12 3]
}Time: O(log n) once you know the spot (O(n) to find it by value) · Extra space: O(1). One swap with the last item, then one climb or one sink along a single branch.
Watch out for
- Only sinking the plug. When the last item belongs to another branch it can be smaller than the new parent and must climb.
- Shifting everything left like in a plain array. That wrecks the parent/child positions.
- Forgetting the special case where the deleted item is the last item. Then there is nothing to plug.
Quick check
- To delete a node from the middle of a heap, which item fills the hole?
- The last item of the array
- The smallest child
- The root
- After plugging, what might the plug have to do?
- Climb or sink (but not both)
- Only climb
- Only sink
- Time to delete when you already know the item's spot?
- O(1)
- O(log n)
- O(n)