cswork / templatesOpen the Line 500 list

STOP 17 · GRAPHS

Shortest Paths and Graph States

Dijkstra with a heap and lazy deletion O((V + E) log V)

Contest ratings Rating 1780–Rating 2201· median Rating 1948(9 of 12 problems rated by zerotrac)

Open the Line 500 list · stop 17 · 12 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 6 companies · in 7 reportsSnap 2, Airbnb 1, Amazon 1, DoorDash 1, Salesforce 1

Warm up with this one

LC 127Word LadderHard
Stuck? Peek at the approach

Model word changes as an unweighted shortest-path problem, controlling neighbor generation and repeated visits.

Key points

  1. The node popped with the smallest tentative distance is final; this only holds when every edge weight is non-negative.
  2. Skip decrease-key: push the new distance and, on pop, discard entries larger than dist (lazy deletion).
  3. With 0/1 weights use deque BFS; with negative weights use Bellman-Ford; when the state carries extra data such as stops used, treat (node, count) as the node.

Common pitfalls

  • Not skipping stale heap entries relaxes the same node again and again and times out on dense graphs.
  • Distances outgrow 32-bit integers, and INT_MAX used as infinity turns negative once w is added.
  • Building a directed graph as undirected (or the reverse) makes every distance wrong.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Dijkstra · weighted shortest paths

What is the shortest distance from A to every node?

421510263A0B∞C∞D∞E∞F∞
0A
∞B
∞C
∞D
∞E
∞F
CurrentDiscovered / computedAnswer
Priority queue (smallest distance first)
A:0
Settled
0 / 6
Current
—
A→F
∞

A starts at distance 0, the rest at ∞. The number under each node is its best known distance.

InvariantThe unsettled node popped from the priority queue already has its shortest distance, as long as no edge is negative.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 127, with it.

Python
import heapq


def dijkstra(n: int, edges: list[tuple[int, int, int]], src: int) -> list[int]:
    """Directed edges (u, v, w) with w >= 0. Unreachable nodes get -1."""
    graph = [[] for _ in range(n)]
    for u, v, w in edges:
        graph[u].append((v, w))
    dist = [float("inf")] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue  # stale entry: u was settled with a shorter distance
        for v, w in graph[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(heap, (dist[v], v))
    return [d if d != float("inf") else -1 for d in dist]
C++
// Directed edges {u, v, w} with w >= 0. Unreachable nodes get -1.
vector<long long> dijkstra(int n, const vector<array<int, 3>>& edges, int src) {
    vector<vector<pair<int, int>>> graph(n);
    for (auto& [u, v, w] : edges) graph[u].push_back({v, w});
    vector<long long> dist(n, LLONG_MAX);
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;  // min-heap
    dist[src] = 0;
    pq.push({0, src});
    while (!pq.empty()) {
        auto [d, u] = pq.top();
        pq.pop();
        if (d > dist[u]) continue;  // stale entry: u was settled with a shorter distance
        for (auto [v, w] : graph[u])
            if (d + w < dist[v]) {
                dist[v] = d + w;
                pq.push({dist[v], v});
            }
    }
    for (auto& d : dist)
        if (d == LLONG_MAX) d = -1;
    return dist;
}
Java
class Solution {
    // Directed edges {u, v, w} with w >= 0. Unreachable nodes get -1.
    long[] dijkstra(int n, int[][] edges, int src) {
        List<List<int[]>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        for (int[] e : edges) graph.get(e[0]).add(new int[] {e[1], e[2]});
        long[] dist = new long[n];
        Arrays.fill(dist, Long.MAX_VALUE);
        PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
        dist[src] = 0;
        pq.offer(new long[] {0, src});
        while (!pq.isEmpty()) {
            long[] top = pq.poll();
            long d = top[0];
            int u = (int) top[1];
            if (d > dist[u]) continue; // stale entry: u was settled with a shorter distance
            for (int[] e : graph.get(u))
                if (d + e[1] < dist[e[0]]) {
                    dist[e[0]] = d + e[1];
                    pq.offer(new long[] {dist[e[0]], e[0]});
                }
        }
        for (int i = 0; i < n; i++) if (dist[i] == Long.MAX_VALUE) dist[i] = -1;
        return dist;
    }
}
Go
import "container/heap"

type item struct{ dist, node int }
type minHeap []item

func (h minHeap) Len() int           { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].dist < h[j].dist }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any)        { *h = append(*h, x.(item)) }
func (h *minHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

// dijkstra takes directed edges {u, v, w} with w >= 0; unreachable nodes get -1.
func dijkstra(n int, edges [][3]int, src int) []int {
	graph := make([][][2]int, n)
	for _, e := range edges {
		graph[e[0]] = append(graph[e[0]], [2]int{e[1], e[2]})
	}
	dist := make([]int, n)
	for i := range dist {
		dist[i] = -1 // not reached yet
	}
	dist[src] = 0
	h := &minHeap{{0, src}}
	for h.Len() > 0 {
		top := heap.Pop(h).(item)
		if top.dist > dist[top.node] {
			continue // stale entry: the node was settled with a shorter distance
		}
		for _, e := range graph[top.node] {
			v, nd := e[0], top.dist+e[1]
			if dist[v] == -1 || nd < dist[v] {
				dist[v] = nd
				heap.Push(h, item{nd, v})
			}
		}
	}
	return dist
}

Common variants

Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

BFS on an implicit graph: states are nodesO(states × moves per state) time · O(states) space

With every edge costing 1, Dijkstra is unnecessary: each state (a lock's four digits, a word, a board) is a node, the states one move away are generated on the spot, and BFS reaches each one first by a shortest path. One dist map records both "seen" and the distance. LC 752 (Open the Lock), LC 127 (Word Ladder), LC 773 (Sliding Puzzle).

Python
from collections import deque


def open_lock(deadends: list[str], target: str) -> int:
    """Fewest wheel turns from "0000" to target, never resting on a deadend (LC 752)."""
    dead = set(deadends)
    if "0000" in dead:
        return -1
    dist = {"0000": 0}  # every state seen so far, with its distance
    q = deque(["0000"])
    while q:
        s = q.popleft()
        if s == target:
            return dist[s]
        for i in range(4):
            for step in (1, -1):  # turn wheel i up or down
                t = s[:i] + str((int(s[i]) + step) % 10) + s[i + 1 :]
                if t not in dead and t not in dist:
                    dist[t] = dist[s] + 1
                    q.append(t)
    return -1
C++
// Fewest wheel turns from "0000" to target, never resting on a deadend (LC 752).
int openLock(const vector<string>& deadends, const string& target) {
    unordered_set<string> dead(deadends.begin(), deadends.end());
    if (dead.count("0000")) return -1;
    unordered_map<string, int> dist{{"0000", 0}};  // every state seen so far, with its distance
    queue<string> q;
    q.push("0000");
    while (!q.empty()) {
        string s = q.front();
        q.pop();
        if (s == target) return dist[s];
        for (int i = 0; i < 4; i++)
            for (int step : {1, 9}) {  // turn wheel i up, or down (+9 is -1 mod 10)
                string t = s;
                t[i] = '0' + (s[i] - '0' + step) % 10;
                if (!dead.count(t) && !dist.count(t)) {
                    dist[t] = dist[s] + 1;
                    q.push(t);
                }
            }
    }
    return -1;
}
Java
class Solution {
    // Fewest wheel turns from "0000" to target, never resting on a deadend (LC 752).
    int openLock(String[] deadends, String target) {
        Set<String> dead = new HashSet<>(Arrays.asList(deadends));
        if (dead.contains("0000")) return -1;
        Map<String, Integer> dist = new HashMap<>(Map.of("0000", 0)); // every state seen so far, with its distance
        Deque<String> q = new ArrayDeque<>(List.of("0000"));
        while (!q.isEmpty()) {
            String s = q.poll();
            if (s.equals(target)) return dist.get(s);
            for (int i = 0; i < 4; i++)
                for (int step : new int[] {1, 9}) { // turn wheel i up, or down (+9 is -1 mod 10)
                    char[] t = s.toCharArray();
                    t[i] = (char) ('0' + (t[i] - '0' + step) % 10);
                    String next = new String(t);
                    if (!dead.contains(next) && !dist.containsKey(next)) {
                        dist.put(next, dist.get(s) + 1);
                        q.offer(next);
                    }
                }
        }
        return -1;
    }
}
Go
// openLock returns the fewest wheel turns from "0000" to target, never resting on a deadend (LC 752).
func openLock(deadends []string, target string) int {
	dead := map[string]bool{}
	for _, d := range deadends {
		dead[d] = true
	}
	if dead["0000"] {
		return -1
	}
	dist := map[string]int{"0000": 0} // every state seen so far, with its distance
	q := []string{"0000"}
	for len(q) > 0 {
		s := q[0]
		q = q[1:]
		if s == target {
			return dist[s]
		}
		for i := 0; i < 4; i++ {
			for _, step := range []byte{1, 9} { // turn wheel i up, or down (+9 is -1 mod 10)
				t := []byte(s)
				t[i] = '0' + (t[i]-'0'+step)%10
				next := string(t)
				if _, seen := dist[next]; !seen && !dead[next] {
					dist[next] = dist[s] + 1
					q = append(q, next)
				}
			}
		}
	}
	return -1
}
Bellman-Ford with a limit on edgesO(k × E) time · O(V) space

When a shortest path may use at most k stops (or edges can be negative), Dijkstra no longer fits: run k + 1 rounds of relaxation, each starting from the previous round's prices, so round i means at most i edges. LC 787 (Cheapest Flights Within K Stops). Without the limit, V - 1 rounds is plain Bellman-Ford, and one more round detects a negative cycle.

Python
def cheapest_within(n: int, flights: list[tuple[int, int, int]], src: int, dst: int, k: int) -> int:
    """Cheapest price from src to dst with at most k stops, i.e. k + 1 flights (LC 787)."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):  # after round i: best prices using at most i flights
        prev = dist[:]  # relax from last round only, so each round adds at most one flight
        for u, v, w in flights:
            if prev[u] + w < dist[v]:
                dist[v] = prev[u] + w
    return -1 if dist[dst] == INF else dist[dst]
C++
// Cheapest price from src to dst with at most k stops, i.e. k + 1 flights (LC 787).
long long cheapestWithin(int n, const vector<array<int, 3>>& flights, int src, int dst, int k) {
    const long long INF = LLONG_MAX / 4;
    vector<long long> dist(n, INF);
    dist[src] = 0;
    for (int round = 0; round <= k; round++) {  // after round i: best prices using at most i flights
        vector<long long> prev = dist;  // relax from last round only, so each round adds at most one flight
        for (auto [u, v, w] : flights)
            if (prev[u] + w < dist[v]) dist[v] = prev[u] + w;
    }
    return dist[dst] == INF ? -1 : dist[dst];
}
Java
class Solution {
    // Cheapest price from src to dst with at most k stops, i.e. k + 1 flights (LC 787).
    long cheapestWithin(int n, int[][] flights, int src, int dst, int k) {
        final long INF = Long.MAX_VALUE / 4;
        long[] dist = new long[n];
        Arrays.fill(dist, INF);
        dist[src] = 0;
        for (int round = 0; round <= k; round++) { // after round i: best prices using at most i flights
            long[] prev = dist.clone(); // relax from last round only, so each round adds at most one flight
            for (int[] f : flights)
                if (prev[f[0]] + f[2] < dist[f[1]]) dist[f[1]] = prev[f[0]] + f[2];
        }
        return dist[dst] == INF ? -1 : dist[dst];
    }
}
Go
// cheapestWithin returns the cheapest price from src to dst with at most k stops (LC 787).
func cheapestWithin(n int, flights [][3]int, src, dst, k int) int {
	const inf = 1 << 60
	dist := make([]int, n)
	for i := range dist {
		dist[i] = inf
	}
	dist[src] = 0
	for round := 0; round <= k; round++ { // after round i: best prices using at most i flights
		prev := append([]int(nil), dist...) // relax from last round only, so each round adds at most one flight
		for _, f := range flights {
			if prev[f[0]]+f[2] < dist[f[1]] {
				dist[f[1]] = prev[f[0]] + f[2]
			}
		}
	}
	if dist[dst] == inf {
		return -1
	}
	return dist[dst]
}
Bitmask BFS: (node, visited set)O(2^n × n²) time · O(2^n × n) space

For the shortest walk that visits every node when there are only a few (n up to about 12): the state is (current node, bitmask of visited nodes), every start goes into the queue at once for a multi-source BFS, and the first time a full mask appears gives the answer. LC 847 (Shortest Path Visiting All Nodes).

Python
from collections import deque


def shortest_path_all_nodes(graph: list[list[int]]) -> int:
    """Length of the shortest walk that visits every node; edges may repeat (LC 847)."""
    n = len(graph)
    full = (1 << n) - 1
    seen = [[False] * (1 << n) for _ in range(n)]  # state (node, mask of visited nodes)
    q = deque()
    for i in range(n):  # every node is a start, at distance 0
        seen[i][1 << i] = True
        q.append((i, 1 << i))
    steps = 0
    while q:
        for _ in range(len(q)):
            u, mask = q.popleft()
            if mask == full:
                return steps
            for v in graph[u]:
                nxt = mask | 1 << v
                if not seen[v][nxt]:
                    seen[v][nxt] = True
                    q.append((v, nxt))
        steps += 1
    return -1
C++
// Length of the shortest walk that visits every node; edges may repeat (LC 847).
int shortestPathAllNodes(const vector<vector<int>>& graph) {
    int n = graph.size(), full = (1 << n) - 1;
    vector<vector<bool>> seen(n, vector<bool>(1 << n, false));  // state (node, mask of visited nodes)
    queue<pair<int, int>> q;
    for (int i = 0; i < n; i++) {  // every node is a start, at distance 0
        seen[i][1 << i] = true;
        q.push({i, 1 << i});
    }
    for (int steps = 0; !q.empty(); steps++)
        for (int k = q.size(); k > 0; k--) {
            auto [u, mask] = q.front();
            q.pop();
            if (mask == full) return steps;
            for (int v : graph[u]) {
                int next = mask | 1 << v;
                if (!seen[v][next]) {
                    seen[v][next] = true;
                    q.push({v, next});
                }
            }
        }
    return -1;
}
Java
class Solution {
    // Length of the shortest walk that visits every node; edges may repeat (LC 847).
    int shortestPathAllNodes(int[][] graph) {
        int n = graph.length, full = (1 << n) - 1;
        boolean[][] seen = new boolean[n][1 << n]; // state (node, mask of visited nodes)
        Deque<int[]> q = new ArrayDeque<>();
        for (int i = 0; i < n; i++) { // every node is a start, at distance 0
            seen[i][1 << i] = true;
            q.offer(new int[] {i, 1 << i});
        }
        for (int steps = 0; !q.isEmpty(); steps++)
            for (int k = q.size(); k > 0; k--) {
                int[] state = q.poll();
                if (state[1] == full) return steps;
                for (int v : graph[state[0]]) {
                    int next = state[1] | 1 << v;
                    if (!seen[v][next]) {
                        seen[v][next] = true;
                        q.offer(new int[] {v, next});
                    }
                }
            }
        return -1;
    }
}
Go
// shortestPathAllNodes returns the length of the shortest walk that visits every node (LC 847).
func shortestPathAllNodes(graph [][]int) int {
	n := len(graph)
	full := 1<<n - 1
	seen := make([][]bool, n) // state (node, mask of visited nodes)
	var q [][2]int
	for i := range seen { // every node is a start, at distance 0
		seen[i] = make([]bool, 1<<n)
		seen[i][1<<i] = true
		q = append(q, [2]int{i, 1 << i})
	}
	for steps := 0; len(q) > 0; steps++ {
		var next [][2]int // the following BFS level
		for _, s := range q {
			if s[1] == full {
				return steps
			}
			for _, v := range graph[s[0]] {
				if mask := s[1] | 1<<v; !seen[v][mask] {
					seen[v][mask] = true
					next = append(next, [2]int{v, mask})
				}
			}
		}
		q = next
	}
	return -1
}

Why it works

  1. Popped means final: the top node u has the smallest tentative distance d among unsettled nodes. Any other route to u must leave the settled set through some unsettled v with distance ≥ d and then add non-negative edges, so it cannot be shorter than d.
  2. Negative edges break that argument. Counterexample: A→B weight 1, A→C weight 2, C→B weight −2. B pops first with distance 1, but the true shortest path A→C→B costs 0. A version that marks popped nodes done returns 1; the lazy-deletion version relaxes B again but loses its running-time guarantee, so negative edges call for Bellman-Ford.
  3. Lazy deletion is safe: a stale entry has d > dist[u], and the shorter entry for u already popped earlier and relaxed its neighbours, so skipping the stale one loses nothing.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
非负权最短路我用 Dijkstra:堆里按当前距离取最小的点,取出即确定,再去松弛它的邻居。之所以取出即确定,是因为别的路径要绕过来,得先经过一个距离不小于它的点,再加非负边,不可能更短。我不用 decrease-key,而是把新距离直接入堆,出堆时跳过比 dist 大的过期条目。复杂度 O((V+E) log V);有负边就换 Bellman-Ford,0/1 边权用双端队列 BFS。
English
For shortest paths with non-negative weights I use Dijkstra: pop the node with the smallest tentative distance, treat it as final, and relax its neighbours. It is final because any other route would have to pass through a node at least as far away and then add non-negative edges. Instead of decrease-key I push the new distance and skip stale entries larger than dist when they pop. That is O((V + E) log V); with negative edges I switch to Bellman-Ford, and with 0/1 weights to a deque BFS.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. A directed graph has negative edges but no negative cycle. Which algorithm finds single-source shortest paths?
  2. In 0-1 BFS (edge weights 0 or 1, using a deque), where do newly reached vertices go?
  3. The graph has V vertices, E edges and non-negative weights. What is the time complexity?
    import heapq
    
    def dijkstra(adj, s):
        dist = {s: 0}
        pq = [(0, s)]
        while pq:
            d, u = heapq.heappop(pq)
            if d > dist[u]:
                continue
            for v, w in adj[u]:
                if d + w < dist.get(v, float('inf')):
                    dist[v] = d + w
                    heapq.heappush(pq, (d + w, v))
        return dist
  4. V = n vertices and E = len(edges) edges. What is the time complexity?
    def bellman_ford(n, edges, s):
        dist = [float('inf')] * n
        dist[s] = 0
        for _ in range(n - 1):
            for u, v, w in edges:
                if dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
        return dist
  5. d is a V×V distance matrix. What is the time complexity?
    def all_pairs(d):
        n = len(d)
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    if d[i][k] + d[k][j] < d[i][j]:
                        d[i][j] = d[i][k] + d[k][j]
        return d

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

import heapq


def dijkstra(n: int, edges: list[tuple[int, int, int]], src: int) -> list[int]:
    """Directed edges (u, v, w) with w >= 0. Unreachable nodes get -1."""
    graph = [[] for _ in range(n)]
                heapq.heappush(heap, (dist[v], v))
    return [d if d != float("inf") else -1 for d in dist]

Practice by stage

This stop's 12 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 6

#ProblemApproachRating
127Word LadderModel word changes as an unweighted shortest-path problem, controlling neighbor generation and repeated visits.
433Minimum Genetic MutationSearch for the fewest substitutions within the finite set of allowed gene strings.
752Open the LockTreat lock combinations as states, handling dead ends and wraparound for individual wheels.Rating 1878
909Snakes and LaddersMap board numbers correctly and distinguish dice moves from forced ladder or snake transitions.Rating 2020
1129Shortest Path with Alternating ColorsInclude the previous edge color in the state to find shortest paths with alternating colors.Rating 1780
743Network Delay TimeUse Dijkstra's algorithm for single-source shortest paths and determine whether every node receives the signal.

Advanced 6

#ProblemApproachRating
773Sliding PuzzleEncode board states and search with BFS, recognizing unreachable permutations.Rating 1815
815Bus RoutesModel search through bus routes or stops and avoid repeatedly scanning the same route.Rating 1964
787Cheapest Flights Within K StopsTrack the stop limit alongside path cost rather than deduplicating states solely by city.Rating 1786
1631Path With Minimum EffortDefine path cost as its maximum edge weight and adapt the shortest-path relaxation rule.Rating 1948
778Swim in Rising WaterUse a minimum-bottleneck path or threshold connectivity to solve reachability as water rises.Rating 2097
847Shortest Path Visiting All NodesInclude the visited-node set in BFS state to find the shortest walk visiting all nodes.Rating 2201

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.