STOP 17 · GRAPHS
Shortest Paths and Graph States
Dijkstra with a heap and lazy deletion O((V + E) log V)
- 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 LadderStuck? Peek at the approach
Model word changes as an unweighted shortest-path problem, controlling neighbor generation and repeated visits.
Key points
- The node popped with the smallest tentative distance is final; this only holds when every edge weight is non-negative.
- Skip decrease-key: push the new distance and, on pop, discard entries larger than dist (lazy deletion).
- 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.
Dijkstra · weighted shortest paths
What is the shortest distance from A to every node?
- 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 -1C++
// 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 -1C++
// 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
- 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.
- 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.
- 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。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.
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
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
| # | Problem | Approach | Rating |
|---|---|---|---|
| 127 | Word Ladder | Model word changes as an unweighted shortest-path problem, controlling neighbor generation and repeated visits. | |
| 433 | Minimum Genetic Mutation | Search for the fewest substitutions within the finite set of allowed gene strings. | |
| 752 | Open the Lock | Treat lock combinations as states, handling dead ends and wraparound for individual wheels. | |
| 909 | Snakes and Ladders | Map board numbers correctly and distinguish dice moves from forced ladder or snake transitions. | |
| 1129 | Shortest Path with Alternating Colors | Include the previous edge color in the state to find shortest paths with alternating colors. | |
| 743 | Network Delay Time | Use Dijkstra's algorithm for single-source shortest paths and determine whether every node receives the signal. |
Advanced 6
| # | Problem | Approach | Rating |
|---|---|---|---|
| 773 | Sliding Puzzle | Encode board states and search with BFS, recognizing unreachable permutations. | |
| 815 | Bus Routes | Model search through bus routes or stops and avoid repeatedly scanning the same route. | |
| 787 | Cheapest Flights Within K Stops | Track the stop limit alongside path cost rather than deduplicating states solely by city. | |
| 1631 | Path With Minimum Effort | Define path cost as its maximum edge weight and adapt the shortest-path relaxation rule. | |
| 778 | Swim in Rising Water | Use a minimum-bottleneck path or threshold connectivity to solve reachability as water rises. | |
| 847 | Shortest Path Visiting All Nodes | Include the visited-node set in BFS state to find the shortest walk visiting all nodes. |
OA questions on this topic 19
- Amazon Fresh — Delivery Grid BFSAmazon
- Find the PathLinkedIn
- Determine the Edit Distance in a Word LadderAdobe
- Grid TraversalSnowflake
- Minimum Clicks Between Wiki PagesSnowflake
- Minimize Path ValueSalesforce
- Simulate Water FlowUber
- Minimum MovesAirbnb
- Closest DashMartDoorDash
- Minimize Path ValuePalantir
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.