Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Shortest paths
EXPERIMENT 41 / 66

When every edge has a cost.

Use a priority queue for nonnegative weighted paths and ignore stale entries.

BY NAVAN SAMI◷ 10 MIN READSTRETCHALGORITHM

01 Model the idea

Dijkstra’s algorithm repeatedly settles the smallest tentative distance. It works when edge costs are nonnegative. A min-heap prioritises the next candidate, and a distance map stores the best cost found so far. This implementation pushes improved distances rather than modifying heap entries in place; outdated entries are skipped when popped.

THE THING THAT MUST STAY TRUE

A settled minimum distance cannot be improved by a later nonnegative route.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
START source distance at zero
POP the smallest tentative distance
SKIP outdated entries
RELAX outgoing nonnegative edges

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

dijkstra.py
import heapq

def distances(graph, start):
    best, queue = {start: 0}, [(0, start)]
    while queue:
        cost, node = heapq.heappop(queue)
        if cost != best[node]: continue
        for neighbour, weight in graph.get(node, []):
            if weight < 0: raise ValueError("Nonnegative weights required")
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour] = candidate
                heapq.heappush(queue, (candidate, neighbour))
    return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
print(distances(graph, "A")["B"])
↳ EXPECTED OUTPUT
3
  1. 1

    A→C→B costs three, improving on the direct edge cost four. The priority queue explores candidates by total cost, not edge count.

  2. 2

    An older candidate for B can remain in the heap after a better route is found. The stale-entry check prevents redundant processing.

  3. 3

    This fixture uses comparable string vertex names, so equal heap costs can compare the second tuple element. Arbitrary vertex objects need a counter tie-breaker. Validate all reachable edge weights and choose a different algorithm if negatives are allowed.

04 Count the cost

TIME

O((V + E) log V) on simple graphs with a binary heap

SPACE

O(V + E), including stale heap entries

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Compare the cost of a direct route with an indirect cheaper route in a small nonnegative graph.

Reveal one possible solution +
one_possible_solution.py
import heapq

def distances(graph, start):
    best, queue = {start: 0}, [(0, start)]
    while queue:
        cost, node = heapq.heappop(queue)
        if cost != best[node]: continue
        for neighbour, weight in graph.get(node, []):
            if weight < 0: raise ValueError("Nonnegative weights required")
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour] = candidate
                heapq.heappush(queue, (candidate, neighbour))
    return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
result = distances(graph, "A")
assert result["B"] == 3
print("Direct: 4; best route:", result["B"])

06 Check your reasoning

QUICK SIGNAL CHECK

What edge-cost restriction does Dijkstra need?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.