Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Implementing decrease-key in a Python binary heap

Priority queues decide which pending item should be handled next: a router request with a short deadline, a delivery with a narrow delivery window, or a job whose business priority has just risen. A binary min-heap supports this pattern efficiently by keeping the smallest key at the root, so each extraction exposes the next candidate without scanning the whole collection. Learn more about Understanding The Dbscan Clustering Algorithm.

Python’s heapq module provides heappush, heappop, and heapify, but it has no public decrease-key operation. The usual workaround is to push a replacement entry and discard the obsolete one later. An indexed binary heap solves the same problem directly by recording each item’s current array position, allowing an existing priority to be lowered and repaired with a sift-up.

Why decrease-key matters

A decrease-key operation changes the priority of an item already inside a priority queue without removing and reinserting it. This matters when many items are waiting and several priorities can change. For example, a scheduler can promote one delayed checkout job while leaving hundreds of unrelated jobs untouched. Algorithms that repeatedly select the next most promising candidate can use the same mechanism; the DBSCAN clustering walkthrough shows how neighbourhood expansion depends on efficient candidate selection.

A lazy-deletion approach with heapq is often simpler: push (new_priority, item_id), then skip stale entries when they reach the root. It works well when updates are rare, but repeated changes can create duplicate heap entries and consume extra memory. An indexed heap keeps one live entry per item, which makes its behaviour easier to reason about when priorities change frequently.

Heap layout and operation costs

In the zero-based array representation, the parent of index i is (i - 1) // 2; its children are 2 * i + 1 and 2 * i + 2. A min-heap maintains the heap-order property: every parent key is no greater than either child key. Alongside the array, the implementation keeps an item_id -> index mapping. The mapping is the “index” that distinguishes this structure from an ordinary heap of values.

Structure Read minimum Insert Remove minimum Decrease an existing key
Sorted list O(1) O(n) O(n) O(n)
Unsorted list O(n) O(1) O(n) O(1) after lookup
Indexed binary min-heap O(1) O(log n) O(log n) O(log n)

The heap therefore provides constant-time access to its minimum, logarithmic insertion and deletion, and logarithmic decrease-key when the position lookup is constant-time on average. Building it from n entries with bottom-up heapification costs O(n), rather than inserting every item separately for O(n log n) total work. Space is O(n) for the array plus O(n) for the position mapping.

Building an indexed Python min-heap

The implementation below stores (priority, item_id) tuples. IDs must be unique and hashable, while priorities must support the comparisons used by the heap. Tracking IDs rather than payload objects keeps the example general: a task ID can point to a record held elsewhere.

class MinHeap:
    def __init__(self, entries=()):
        self._heap = []
        self._positions = {}

        for priority, item_id in entries:
            if item_id in self._positions:
                raise ValueError("Duplicate item ID")
            self._heap.append((priority, item_id))
            self._positions[item_id] = len(self._heap) - 1

        self._heapify()

    def __len__(self):
        return len(self._heap)

    def _swap(self, i, j):
        self._heap[i], self._heap[j] = self._heap[j], self._heap[i]
        self._positions[self._heap[i][1]] = i
        self._positions[self._heap[j][1]] = j

    def _sift_up(self, index):
        while index > 0:
            parent = (index - 1) // 2
            if self._heap[parent][0] <= self._heap[index][0]:
                break
            self._swap(parent, index)
            index = parent

    def _sift_down(self, index):
        size = len(self._heap)

        while True:
            left = 2 * index + 1
            if left >= size:
                break

            child = left
            right = left + 1
            if right < size and self._heap[right][0] < self._heap[left][0]:
                child = right

            if self._heap[index][0] <= self._heap[child][0]:
                break

            self._swap(index, child)
            index = child

    def _heapify(self):
        for index in range(len(self._heap) // 2 - 1, -1, -1):
            self._sift_down(index)

    def push(self, priority, item_id):
        if item_id in self._positions:
            raise ValueError("Duplicate item ID")

        self._heap.append((priority, item_id))
        index = len(self._heap) - 1
        self._positions[item_id] = index
        self._sift_up(index)

    def pop(self):
        if not self._heap:
            raise IndexError("pop from an empty heap")

        root = self._heap[0]
        last = self._heap.pop()
        del self._positions[root[1]]

        if self._heap:
            self._heap[0] = last
            self._positions[last[1]] = 0
            self._sift_down(0)

        return root

    def peek(self):
        if not self._heap:
            raise IndexError("peek from an empty heap")
        return self._heap[0]

    def decrease_key(self, item_id, priority):
        index = self._positions[item_id]
        old_priority = self._heap[index][0]

        if priority > old_priority:
            raise ValueError("A min-heap key can only decrease")

        self._heap[index] = (priority, item_id)
        self._sift_up(index)

After a key decreases, only its relationship with ancestors can violate heap order, so _sift_up compares the changed entry with its parent and swaps it upward. Every swap also updates the position mapping, preventing stale indices after later extractions. The constructor performs a bottom-up heapify, while push, pop, and peek provide the normal queue operations.

Implementing the decrease-key update

The update first checks that the ID exists in the position dictionary. It rejects a numerically larger priority because this is a min-heap and the operation is specifically a decrease. After replacing the tuple, _sift_up restores the heap-order property. No downward repair is needed: lowering a node cannot make it greater than its descendants. An unknown ID raises KeyError from the dictionary lookup.

jobs = MinHeap([(5, "pick"), (2, "pack"), (8, "dispatch")])

jobs.decrease_key("dispatch", 1)

assert jobs.peek() == (1, "dispatch")
assert jobs.pop() == (1, "dispatch")

Equal priorities need a deliberate policy. The sample treats them as interchangeable, but its sift methods compare priorities only. A production queue can add a monotonically increasing sequence number as a tie-breaker, preserving first-in, first-out order among equal priorities. If a priority may rise as well as fall, use a general update_key method that performs a sift-up after a decrease and a sift-down after an increase.

Correctness, edge cases, and tests

The central invariant has two parts: the array is heap-ordered, and the position dictionary points to the exact current location of every stored ID. push appends an entry and moves it upward only while its parent has a larger key. pop replaces the root with the last entry, then moves that entry downward until the local ordering rule is restored. Both repairs preserve both invariants.

A decrease can only create a violation with an ancestor, so moving the changed entry upward is sufficient. The dictionary must be updated during every swap, not merely after the repair finishes, because each intermediate position is observable inside the helper. Backtracking solvers use similar candidate management: the subset sum backtracking guide illustrates how selecting and pruning candidates can avoid exploring unhelpful branches.

Tests should cover an empty heap, one element, updates at the root and deep in the tree, equal keys, duplicate IDs, missing IDs, and an attempted increase. Comparing extracted entries against sorted(entries) provides a simple oracle for random inputs. Avoid NaN priorities because its unusual comparison behaviour can undermine the ordering assumptions used by sift operations.

Using heaps in Australian systems

Australian product teams encounter this pattern in logistics, support, and real-time event processing. In a Melbourne warehouse, pick, pack, and dispatch jobs can form a min-heap; if dispatch receives a new commercial deadline, its priority can fall and the job can move toward the root. A Sydney service can use the same structure to choose the next request from several queues.

Everyday transport systems offer another concrete example. Opal and Myki taps are routine for commuters in Sydney and Melbourne, and transit feeds turn those events into timestamped work. For the Australian grocery market, tools serving retailers such as Woolworths and Coles must also order short-lived fulfilment tasks without letting obsolete priority records accumulate. These scenarios favour one live entry per task when updates are common.

Operational data needs separate attention from the data structure. If task IDs can be linked to customers or orders, an Australian deployment should consider the Privacy Act 1988 and the Australian Privacy Principles. Keep personal details out of priority keys where possible, restrict access to linked records, and define retention rules for queues that may contain identifiable information. The heap should accelerate processing, not weaken privacy controls.

Practical recommendations for Python teams

Before adopting an indexed heap, settle the API and operational constraints:

An indexed binary heap is therefore a strong fit when priorities change often and stale work must not accumulate. For stable priorities, standard heapq remains simpler and avoids maintaining a second index structure.