commonwrite
← All stories

Day 30: Dijkstra's Shortest Path | Heap Lazy Deletion & Greedy Invariants

Greedy relaxation invariants, binary heap lazy deletion, negative-edge counterexamples, and O((V+E) log V) routing.

Why does Google Maps find the fastest highway route across a continent in milliseconds—and why does a single negative road weight shatter Dijkstra's greedy guarantee?


1. In 30 Seconds

Dijkstra's Algorithm finds the shortest path from a starting source vertex to every other vertex in a weighted graph with non-negative edge weights ($w \ge 0$). Think of it as an expanding ripple of known shortest distances: at every step, a Min-Heap (Priority Queue) extracts the closest unsettled node, locks in its minimum distance permanently, and relaxes [attempts to improve the best-known distance estimate of] its outgoing neighbors. Using a binary heap and lazy deletion, Dijkstra runs in $O((V + E) \log V)$ time.


2. The Real-World Analogy: Water Flowing Through Connected Pipes

Imagine a network of cities connected by water pipes of varying lengths (in kilometers), where water flows at exactly 1 km per minute.

  • You turn on the main valve at City 0 at time $t = 0$.
  • Water rushes down all pipes leaving City 0 simultaneously. Because every pipe has a non-negative length, water can never travel backward in time.
  • Whichever city gets wet first (say, City 2 at $t = 3$ minutes) is 100% guaranteed to have received water via its shortest possible route—any detour through another city would take at least 3 minutes plus extra pipe length!
  • The instant water hits a city, it immediately branches out through that city's outgoing pipes until the entire network is flooded.

3. Picture This

Diagram 1: Greedy Relaxation & Priority Queue Frontier

Weighted Directed Graph:
       (4)          (1)
  [0] -----> [1] --------> [3]
   |          ^             ^
   | (1)      | (2)         | (5)
   v          |             |
  [2] --------+-------------+

Initial dist[]: [0, INF, INF, INF]   | Min-Heap: [(0, node=0)]

Step 1: Pop (0, node=0). Relax 0->1 (4) and 0->2 (1).
        dist[]: [0, 4, 1, INF]       | Min-Heap: [(1, 2), (4, 1)]

Step 2: Pop (1, node=2). Relax 2->1 (1+2=3 < 4! Update!) & 2->3 (1+5=6).
        dist[]: [0, 3, 1, 6]         | Min-Heap: [(3, 1), (4, 1), (6, 3)]
                                                       ^-- Stale entry (lazy skip!)

Step 3: Pop (3, node=1). Relax 1->3 (3+1=4 < 6! Update!).
        dist[]: [0, 3, 1, 4]         | Min-Heap: [(4, 1), (4, 3), (6, 3)]

Step 4: Pop (4, node=1) -> 4 > dist[1] (3) -> SKIPPED in O(1)!
Step 5: Pop (4, node=3) -> Finalized!
Step 6: Pop (6, node=3) -> 6 > dist[3] (4) -> SKIPPED in O(1)!

Final Shortest Distances from 0: [0, 3, 1, 4]

Walkthrough: Notice how node 1 initially enters the heap with distance 4, and later gets pushed again with a better distance 3. Instead of searching inside the binary heap to delete (4, 1) (which takes $O(V)$), we leave it there and skip it in $O(1)$ when popped via if d > dist[u]: continue.

Diagram 2: Why Negative Edges Break Dijkstra's Greedy Invariant

Counterexample Graph:
        (5)
  [0] -------> [2]
   |            ^
   | (10)       | (-8)
   v            |
  [1] ----------+

1. Dijkstra pops (5, node=2) FIRST and locks dist[2] = 5!
2. Later, Dijkstra pops (10, node=1), follows 1->2 (-8), and discovers
   path 0 -> 1 -> 2 costs 10 + (-8) = 2 < 5!
3. Greedy assumption shattered: future paths CAN shrink total cost!

Walkthrough: Dijkstra's correctness proof relies strictly on $w(u, v) \ge 0$ so path lengths never decrease as you add edges. If negative edges exist, switch to Bellman-Ford ($O(VE)$) or SPFA.


4. How It Actually Works (First Principles & Invariants)

  1. The Settled-Node Invariant: Every time the Min-Heap pops `(d, u)` where `d == dist[u]`, `dist[u]` is mathematically guaranteed to equal the true shortest-path distance $\delta(s, u)$. Proof by contradiction: if a shorter path existed, it would have to exit the settled set $S$ through some frontier vertex $y$ whose distance is already $\ge d$, and since all remaining edges are $\ge 0$, no extension could ever beat $d$.
  2. Lazy Deletion vs. Decrease-Key: Standard binary heaps (including Python's `heapq`) do not support $O(\log V)$ arbitrary `decrease_key`. Pushing duplicate `(new_dist, v)` tuples and discarding stale pops (`if d > dist[u]: continue`) keeps heap size $\le E$, running in $O((V + E) \log E) = O((V + E) \log V)$ with zero pointer bookkeeping.
  3. Early Exit for Single-Pair Queries: When routing between a specific `source` and `target` (like GPS navigation), you can `return dist[target]` the exact moment `target` is popped from the heap—often skipping 80%+ of the graph.
  4. Dense vs. Sparse Graph Complexity: On dense graphs ($E \approx V^2$), an $O(V^2)$ array-scan Dijkstra (without a heap) beats heap Dijkstra ($O(V^2 \log V)$) by avoiding logarithmic heap overhead.

5. Show Me The Code

Here is a complete, production-ready Python implementation of Dijkstra's Shortest Path with lazy deletion and path reconstruction.

# Day 30: Dijkstra's Shortest Path — Binary Heap + Lazy Deletion + Path Reconstruction

import heapq


def dijkstra_shortest_paths(num_nodes, edges, source):
    """
    Computes shortest distances and parent pointers from `source` to all nodes
    in a directed/undirected graph with non-negative edge weights (w >= 0).
    Time Complexity: O((V + E) log V)
    Space Complexity: O(V + E)
    """
    adj = [[] for _ in range(num_nodes)]
    for u, v, weight in edges:
        if weight < 0:
            raise ValueError("Dijkstra requires non-negative edge weights!")
        adj[u].append((v, weight))

    INF = float("inf")
    dist = [INF] * num_nodes
    parent = [-1] * num_nodes
    dist[source] = 0

    # Min-Heap stores tuples of (current_best_distance, node)
    min_heap = [(0, source)]

    while min_heap:
        d, u = heapq.heappop(min_heap)

        # Lazy Deletion: ignore outdated heap entries superseded by a shorter path
        if d > dist[u]:
            continue

        # Edge Relaxation: check if routing through `u` improves neighbor `v`
        for v, weight in adj[u]:
            new_dist = d + weight
            if new_dist < dist[v]:
                dist[v] = new_dist
                parent[v] = u
                heapq.heappush(min_heap, (new_dist, v))

    return dist, parent


def reconstruct_path(parent, target):
    path = []
    curr = target
    while curr != -1:
        path.append(curr)
        curr = parent[curr]
    return path[::-1]


if __name__ == "__main__":
    road_network = [
        (0, 1, 4),
        (0, 2, 1),
        (2, 1, 2),
        (1, 3, 1),
        (2, 3, 5),
    ]
    distances, parents = dijkstra_shortest_paths(4, road_network, source=0)
    print("Shortest distances from 0:", distances)            # [0, 3, 1, 4]
    print("Optimal path 0 -> 3:      ", reconstruct_path(parents, 3))  # [0, 2, 1, 3]

6. Dry Run

Tracing dijkstra_shortest_paths(4, [(0,1,4), (0,2,1), (2,1,2), (1,3,1), (2,3,5)], 0):

StepPopped (d, u)Actiondist[] Arraymin_heap State
1(0, 0)Relax 0->1 (4), 0->2 (1)[0, 4, 1, INF][(1, 2), (4, 1)]
2(1, 2)Relax 2->1 (3 < 4), 2->3 (6)[0, 3, 1, 6][(3, 1), (4, 1), (6, 3)]
3(3, 1)Relax 1->3 (4 < 6)[0, 3, 1, 4][(4, 1), (4, 3), (6, 3)]
4(4, 1)4 > dist[1] (3) -> Skip stale[0, 3, 1, 4][(4, 3), (6, 3)]
5(4, 3)No outgoing edges[0, 3, 1, 4][(6, 3)]
6(6, 3)6 > dist[3] (4) -> Skip stale[0, 3, 1, 4][]

7. Speed & Memory

Each edge triggers at most one heap push ($O(\log E)$), and each heap entry is popped at most once ($O(\log E)$). Since $E \le V^2$, $\log E \le 2 \log V$, giving $O((V + E) \log V)$ total runtime.

ImplementationTime ComplexitySpace ComplexityBest Scenario
Binary Heap + Lazy Deletion$O((V + E) \log V)$$O(V + E)$Sparse real-world graphs (road networks, routing tables).
Unsorted Array Scan$O(V^2)$$O(V^2)$Dense graphs where $E \approx V^2$.
Bellman-Ford (Fallback)$O(V \cdot E)$$O(V + E)$Graphs with negative edge weights or negative-cycle detection.

8. Where You'll See It In Real Life

  1. GPS Navigation & Ride-Hailing Dispatch (Google Maps, Uber): Road intersections are vertices and live travel times (in seconds) are non-negative edge weights; variants like Bidirectional Dijkstra and A* compute fastest ETAs in milliseconds.
  2. Internet Packet Routing (OSPF Protocol): Open Shortest Path First routers run Dijkstra continuously to compute lowest-latency IP routing tables across autonomous network topologies.
  3. Airline & Railway Fare Optimizers: Finding cheapest multi-leg flight itineraries where ticket prices ($w \ge 0$) act as edge weights.

9. Traps To Avoid

  • Trap 1: Running Dijkstra on a graph with negative edge weights.
    Fix: Never use Dijkstra if any edge weight is $< 0$; use Bellman-Ford instead.
  • Trap 2: Omitting the stale-entry check if d > dist[u]: continue.
    Fix: Without this line, outdated heap entries re-scan all outgoing edges of u, degrading worst-case runtime to $O(V \cdot E \log V)$ (TLE on dense graphs!).
  • Trap 3: Putting (node, dist) instead of (dist, node) in Python's heapq.
    Fix: Python compares tuples element-by-element starting at index `0`—always put distance first!
  • Trap 4: Marking nodes visited when pushing to the heap instead of when popping.
    Fix: A node's distance can improve multiple times while sitting in the heap; only finalize it when popped!

10. Practice

  1. Easy (Network Delay Time): Given $N$ network nodes, directed signal travel times, and source node $K$, return how long it takes for all nodes to receive the signal (or -1 if unreachable). Hint: Run Dijkstra from $K$ and return max(dist[1:]).
  2. Medium (Path With Minimum Effort): Given a 2D height grid, move from top-left to bottom-right minimizing the maximum absolute height difference between adjacent cells. Hint: Model cell transitions as edges with weight abs(h1 - h2) and replace d + weight with max(d, weight) in Dijkstra!
  3. Hard (Cheapest Flights Within K Stops): Find the cheapest flight from src to dst with at most $K$ intermediate stops. Hint: Expand the state tuple in your heap to (cost, stops, city) and track best_stops[city] so you don't prune a slightly pricier path that uses fewer stops!

11. TL;DR

  • Dijkstra's Algorithm finds shortest paths from a single source in $O((V + E) \log V)$ time whenever all edge weights are non-negative ($w \ge 0$).
  • Always pair a Min-Heap storing (dist, node) with lazy deletion (if d > dist[u]: continue).
  • Negative edge weights shatter Dijkstra's greedy settled-node invariant—switch to Bellman-Ford when weights can be negative.

12. References Consulted


13. Covered Log Update

Already covered: Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue, Trie, Graph representations, BFS, Depth-First Search (DFS), Topological Sort, Union-Find, Dijkstra's Shortest Path.