Data Structures · Visualization

Heap Construction: Decrease Key

Heap Construction

Lowering a node's value (or raising it in a max-heap) can break the heap rule with its parent only — the subtree below is still fine. Time: O(log n) — at most the tree height. Space: O(1) extra.

Big-O: Bottom-up build O(n); decrease-key O(log n).

Heap Construction: Decrease Key

Heap Construction

Lowering a node's value (or raising it in a max-heap) can break the heap rule with its parent only — the subtree below is still fine. So instead of rebuilding, the node bubbles up: swap with the parent while the order is violated. Dijkstra's algorithm leans on exactly this operation.

How Decrease Key Works

  1. Change the value at index i in place.
  2. Compare with the parent at (i−1)/2.
  3. While the heap order is violated, swap upward.
  4. Stop at the root or when the parent is correctly ordered.

Decrease Key Worked Example

Input: Max-heap [10, 5, 3, 4, 1], raise index 4 from 1 to 9

  1. Set index 4 → 9: [10, 5, 3, 4, 9].
  2. Parent index 1 is 5 < 9 → swap → [10, 9, 3, 4, 5].
  3. Parent index 0 is 10 ≥ 9 → stop.
  4. Heap valid again after 1 bubble-up.

Output: Max-heap: [10, 9, 3, 4, 5]

Try your own input
Heap Construction: Introduction
Bottom-up heapify beats repeated insert: O(n), in place.
7
0
2
1
9
2
4
3
1
4
8
5
Swapping pair
Heap Construction: Introduction
Press ▶ Run to watch it step by step.
Python · Heap Construction in Code
def decrease_key(a, i, v):
    a[i] = v
    while i > 0:
        p = (i - 1) // 2
        if a[p] >= a[i]: break
        a[p], a[i] = a[i], a[p]  # bubble up
        i = p                     # O(log n)
# example: decrease 9 at index 4 on [10, 5, 3, 4, 1]
Input: Max-heap [10, 5, 3, 4, 1], raise index 4 from 1 to 9

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Decrease Key Time & Space Complexity

TimeO(log n) — at most the tree height
SpaceO(1) extra

When to Use Decrease Key

  • Dijkstra relaxing a shorter distance already in the queue
  • Live leaderboards bumping a player's score upward

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.