Single-Source Shortest Distances to Query Nodes
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given a directed network with n vertices numbered 0 through n - 1. Each element [u, v, w] in edges describes a one-way link from vertex u to vertex v with strictly positive travel cost w.
def shortest_distances_to_targets(
n: int,
edges: List[List[int]],
source: int,
targets: List[int],
) -> List[int]:
Starting at vertex source, compute the minimum total travel cost to reach each vertex listed in targets:
- Return a list of length
len(targets)in the exact order oftargets, where indexkgives the minimum cost of a directed walk fromsourcetotargets[k]. - Reaching
sourcefrom itself requires0edges and has cost0. - Whenever no directed route leads from
sourcetotargets[k], record-1at indexk.
Examples
Example 1
Input:
n = 5
edges = [[0, 1, 9], [0, 2, 2], [2, 1, 3], [1, 3, 4], [2, 3, 11], [3, 4, 2]]
source = 0
targets = [1, 3, 4]
Output: [5, 9, 11]
- Best route to
1:0 -> 2 -> 1with cost2 + 3 = 5(beating the direct edge0 -> 1of cost9). - Best route to
3:0 -> 2 -> 1 -> 3with cost2 + 3 + 4 = 9(beating0 -> 2 -> 3of cost2 + 11 = 13). - Best route to
4:0 -> 2 -> 1 -> 3 -> 4with cost9 + 2 = 11.
Example 2
Input:
n = 4
edges = [[1, 2, 6], [2, 3, 4], [0, 1, 3]]
source = 1
targets = [1, 3, 0]
Output: [0, 10, -1]
- Vertex
1is the starting vertex (0). - Vertex
3is reached along1 -> 2 -> 3with cost6 + 4 = 10. - Link
[0, 1, 3]points from0into1and cannot be traversed backward, so0is unreachable (-1).
Example 3
Input:
n = 5
edges = [[2, 3, 8], [2, 3, 3], [3, 2, 5], [0, 1, 4]]
source = 2
targets = [3, 4, 0, 3]
Output: [3, -1, -1, 3]
- Between the parallel links
2 -> 3, cost3beats cost8, and both occurrences of3intargetsreceive3. - Vertices
4and0have no incoming path from2, so both receive-1.
Constraints
1 <= n <= 10^50 <= len(edges) <= 2 * 10^5len(edges[i]) == 30 <= u, v < n1 <= w <= 10^90 <= source < n1 <= len(targets) <= n
Step-by-step walkthrough
Understand the graph and the goal
We have
nnodes labeled0throughn - 1and a list of one-way roadsedges[i] = [u, v, w], meaning you can travel fromutov(notvtou) at positive costw >= 1. Given one starting nodesourceand a listtargets, we must return the shortest total distance fromsourceto each node intargets, keeping the exact order oftargetsand returning-1for any target that cannot be reached.Look at Example 1 (
source = 0,targets = [1, 3, 4]):9 (0) -----> (1) -----> (3) -----> (4) | ^ 4 ^ 2 2 | 3 | | 11 +-------> (2) --------+ Shortest paths from 0: 0 -> 2 cost = 2 0 -> 2 -> 1 cost = 2 + 3 = 5 (beats the direct 0 -> 1 edge of cost 9!) 0 -> 2 -> 1 -> 3 cost = 5 + 4 = 9 (beats 0 -> 2 -> 3 of cost 2 + 11 = 13!) 0 -> ... -> 4 cost = 9 + 2 = 11Keep three details from the constraints in mind: - Graph size: Up to
n = 10^5nodes andm = 2 * 10^5edges, so we need anO((n + m) log m)algorithm, notO(n * m). - Large distances: A chain of10^5edges of weight10^9reaches roughly10^14. Pythonintvalues grow automatically without overflow (in C++ or Java you would need a 64-bitlong long). - Parallel edges and cycles: Multiple edges between the same(u, v)pair or cycles back to visited nodes can appear and must work naturally.Why plain BFS and Bellman-Ford fall short
Two common graph searches do not fit this problem:
- Plain Breadth-First Search (BFS) ignores edge weights. BFS explores in order of fewest edges, so on Example 1 it visits node
1via the single edge0 -> 1(distance9) and misses the two-edge shortcut0 -> 2 -> 1(distance5). - Bellman-Ford is too slow. Checking all
medgesn - 1times takesO(n * m)operations—up to10^5 × 2 * 10^5 = 2 * 10^10steps, which will time out. - Searching separately per target wastes work.
targetscan contain up tonentries. Running one single-source search fromsourcecomputes the shortest distance to every node in the graph at once, answering all targets in a single pass.
- Plain Breadth-First Search (BFS) ignores edge weights. BFS explores in order of fewest edges, so on Example 1 it visits node
Key idea: settle the closest node next with Dijkstra's algorithm
Because every edge weight is positive (
w >= 1), taking more edges can never reduce a path's total distance. Dijkstra's algorithm exploits that fact:- Track
dist[node], the shortest distance fromsourcetonodediscovered so far (0forsource,-1for unreached nodes). - Repeatedly pick the unexpanded node with the smallest
distvalue and lock its distance in as final ("settle" it). - Why is that node's distance guaranteed to be final? Any alternative path from
sourcewould first have to reach some other unsettled node—whose distance is already at least as large—and then add one or more positive edge weights, so it can never beat the distance we just picked.
To always pull out the smallest tentative distance in
O(log m)time, we store(distance_so_far, node)pairs in a min-heap (heapq). Python'sheapqcannot edit an existing entry inside the heap when we discover a shorter path to a node, so we use lazy deletion: - Push the new(shorter_dist, neighbor)pair onto the heap and leave the old pair inside. - Later, when an old pair(current_dist, node)pops, checkif current_dist > dist[node]: continueand skip it.- Track
Build an adjacency list
Scanning the entire
edgeslist every time we visit a node would be far too slow. Instead, we group outgoing edges by their starting node in an adjacency list, wheregraph[u]stores(neighbor, weight)for every edgeu -> neighbor:def build_graph(n: int, edges: List[List[int]]) -> List[List[Tuple[int, int]]]: # graph[u]: list of (neighbor, weight) pairs for all outgoing edges u -> neighbor. graph: List[List[Tuple[int, int]]] = [[] for _ in range(n)] for u, v, weight in edges: graph[u].append((v, weight)) return graphIf there are multiple parallel edges between
uandv, we simply keep all of them ingraph[u]—the cheapest one will naturally win when edges are checked.Code Dijkstra and answer the targets
In
dijkstra, storing-1for unreached nodes keeps every entry an exactint(nofloat("inf")conversions) and matches the-1output required for unreachable targets.Notice the strict inequality
candidate_dist < dist[neighbor]when relaxing an edge: if two paths reachneighborwith the exact same cost, we do not push a second copy onto the heap, guaranteeing every node has its outgoing edges scanned at most once.def dijkstra(graph: List[List[Tuple[int, int]]], source: int) -> List[int]: # dist[node]: best known distance from `source` to `node`, or -1 if unreached. dist = [-1] * len(graph) dist[source] = 0 # min_heap: priority queue of (distance_so_far, node) ordered by smallest distance. min_heap = [(0, source)] while min_heap: current_dist, node = heapq.heappop(min_heap) # Lazy deletion: if we already found a strictly shorter path to `node` after # this pair was pushed, this heap entry is outdated and must be skipped. if current_dist > dist[node]: continue # Relax every outgoing edge `node -> neighbor` of positive cost `weight`. for neighbor, weight in graph[node]: candidate_dist = current_dist + weight # Strict `<` (not `<=`) avoids duplicate heap pushes on tied paths, # ensuring each node is expanded at most once. if dist[neighbor] == -1 or candidate_dist < dist[neighbor]: dist[neighbor] = candidate_dist heapq.heappush(min_heap, (candidate_dist, neighbor)) return dist def shortest_distances_to_targets( n: int, edges: List[List[int]], source: int, targets: List[int], ) -> List[int]: # Phase 1: Group outgoing edges by start node so neighbor lookup is fast. graph = build_graph(n, edges) # Phase 2: Compute shortest distances from `source` to all `n` nodes in one pass. dist = dijkstra(graph, source) # Phase 3: Read off each requested target in order (-1 is already stored if unreachable). answers = [] for target in targets: answers.append(dist[target]) return answersTrace Example 1 step by step
Here is every heap pop on Example 1 (
source = 0,diststarts as[0, -1, -1, -1, -1]):Popped Action dist after step -------- ------------------------------------------------ ------------------- (0, 0) 0->1 sets dist[1]=9, push (9,1) 0->2 sets dist[2]=2, push (2,2) [0, 9, 2, -1, -1] (2, 2) 2->1 improves dist[1] from 9 to 5, push (5,1) 2->3 sets dist[3]=13, push (13,3) [0, 5, 2, 13, -1] (5, 1) 1->3 improves dist[3] from 13 to 9, push (9,3) [0, 5, 2, 9, -1] (9, 1) 9 > dist[1] (5) -> stale entry, skip! [0, 5, 2, 9, -1] (9, 3) 3->4 sets dist[4]=11, push (11,4) [0, 5, 2, 9, 11] (11, 4) no outgoing edges [0, 5, 2, 9, 11] (13, 3) 13 > dist[3] (9) -> stale entry, skip! [0, 5, 2, 9, 11]Reading
targets = [1, 3, 4]fromdist = [0, 5, 2, 9, 11]returns[5, 9, 11].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def build_graph(n: int, edges: List[List[int]]) -> List[List[Tuple[int, int]]]: # graph[u]: list of (neighbor, weight) pairs for all outgoing edges u -> neighbor. graph: List[List[Tuple[int, int]]] = [[] for _ in range(n)] for u, v, weight in edges: graph[u].append((v, weight)) return graph def dijkstra(graph: List[List[Tuple[int, int]]], source: int) -> List[int]: # dist[node]: best known distance from `source` to `node`, or -1 if unreached. dist = [-1] * len(graph) dist[source] = 0 # min_heap: priority queue of (distance_so_far, node) ordered by smallest distance. min_heap = [(0, source)] while min_heap: current_dist, node = heapq.heappop(min_heap) # Lazy deletion: if we already found a strictly shorter path to `node` after # this pair was pushed, this heap entry is outdated and must be skipped. if current_dist > dist[node]: continue # Relax every outgoing edge `node -> neighbor` of positive cost `weight`. for neighbor, weight in graph[node]: candidate_dist = current_dist + weight # Strict `<` (not `<=`) avoids duplicate heap pushes on tied paths, # ensuring each node is expanded at most once. if dist[neighbor] == -1 or candidate_dist < dist[neighbor]: dist[neighbor] = candidate_dist heapq.heappush(min_heap, (candidate_dist, neighbor)) return dist def shortest_distances_to_targets( n: int, edges: List[List[int]], source: int, targets: List[int], ) -> List[int]: # Phase 1: Group outgoing edges by start node so neighbor lookup is fast. graph = build_graph(n, edges) # Phase 2: Compute shortest distances from `source` to all `n` nodes in one pass. dist = dijkstra(graph, source) # Phase 3: Read off each requested target in order (-1 is already stored if unreachable). answers = [] for target in targets: answers.append(dist[target]) return answers✅ Submit now — all tests should pass.
Intuition & how it works
Picture pouring water into the source junction of a network of one-way pipes of different lengths: if water flows at a steady speed, the very first stream to reach any junction has traveled along the shortest possible route, even if it took two short pipes instead of one long pipe. Here the network is a directed weighted graph—a set of nodes connected by one-way edges that each carry a positive travel cost—stored in an adjacency list (a per-node list of outgoing (neighbor, weight) pairs). Dijkstra's algorithm simulates that expanding wavefront using a min-heap—a priority queue that always hands back the smallest-distance pair (distance, node) in O(log size) time—and performs edge relaxation, meaning it checks each outgoing edge node -> neighbor to see if current_dist + weight improves neighbor's best known distance. Because updating an existing entry inside Python's heapq is awkward, we use lazy deletion: we simply push a fresh (shorter_dist, neighbor) pair onto the heap and skip any older, larger-distance copy when it eventually pops.
A naive Breadth-First Search fails because it minimizes the number of edges rather than the sum of weights, picking a single costly edge over a cheaper multi-edge detour. Re-checking every edge n - 1 times or running a brand-new graph search for each entry in targets also falls short because 10^5 nodes and 2 * 10^5 edges would require billions of operations, whereas one Dijkstra run from source answers every target at once.
Consider a tiny 3-node slice of Example 1 with source = 0, targets = [1, 2], and edges 0 -> 1 (cost 9), 0 -> 2 (cost 2), 2 -> 1 (cost 3):
1. Start: dist = [0, -1, -1], heap [(0, 0)].
2. Pop (0, 0): Relax 0 -> 1 (dist[1] = 9, push (9, 1)) and 0 -> 2 (dist[2] = 2, push (2, 2)).
3. Pop (2, 2): Node 2 has the smallest tentative distance (2), so it is settled next; relaxing 2 -> 1 gives 2 + 3 = 5 < 9, updating dist[1] = 5 and pushing (5, 1).
4. Pop (5, 1), then (9, 1): (5, 1) settles node 1 at distance 5; when (9, 1) pops next, 9 > dist[1] marks it stale so we skip it and return [dist[1], dist[2]] = [5, 2].
Complexity
- Time: O(n + m log m), where
nis the number of nodes andmis the number of edges. Building the adjacency list anddistarray takesO(n + m)time; each node is expanded from the heap at most once, so each of themedges triggers at most oneheappush, giving at mostm + 1heap pushes and pops atO(log m)each; finally, looking uplen(targets)answers (len(targets) <= n) takesO(len(targets))time. - Space: O(n + m). The adjacency list stores
nlists containingm(neighbor, weight)tuples in total,distholdsnintegers,min_heapholds at mostm + 1pairs, and the output list holdslen(targets) <= nintegers.
Edge cases
sourceappears intargets:dist[source]starts at0and positive edge weights can never lower it, so it cleanly returns0.- Unreachable nodes or empty
edges: Unreached nodes keep their initial-1value indist. - Parallel edges between the same
(u, v)pair: Keeping all of them ingraph[u]works automatically because only the smallestcurrent_dist + weightsurvives indist[v]. - Self-loops (
u -> u) and directed cycles: Because every weight is at least1,current_dist + weightaround a self-loop or back to a settled node is strictly larger than its already-recordeddistand is ignored. - Repeated entries in
targets: Reading[dist[t] for t in targets]preserves duplicates and the exact input order. - 64-bit distance sums: A path of
99,999edges of weight10^9totals roughly10^14, which fits automatically in Pythonint(and requires 64-bit integers in statically typed languages).
Common mistakes
- Using unweighted BFS: Minimizes hop count instead of total weight, returning
9instead of5for node1in Example 1. - Marking nodes "visited" on push instead of settling on pop: Locks in the first path discovered to a node (
0 -> 1with cost9) and blocks shorter multi-edge paths (0 -> 2 -> 1with cost5) discovered later. - Using
<=instead of<when relaxing edges:candidate_dist <= dist[neighbor]pushes duplicate heap entries whenever two paths tie in distance, which can cause exponential re-expansion on diamond-shaped graphs. - Forgetting the
current_dist > dist[node]stale-entry check: Does not break correctness with positive weights, but re-scans all outgoing edges ofnodefor every outdated heap copy and can time out on dense graphs. - Initializing
distwithfloat("inf")and forgetting to translate back to-1: Causes unreachable targets to returninfinstead of-1.
Alternative approaches
- Early exit once all distinct targets are settled: Keep a
remaining = set(targets)set and removenodewhen it is popped for the first time (current_dist == dist[node]); onceremainingbecomes empty, break out of the heap loop early. Worst-case complexity staysO(n + m log m)(for instance when a target is unreachable), but queries where all targets sit nearsourcefinish much sooner. - Bellman-Ford algorithm: Relaxes all
medgesn - 1times without a heap inO(n * m)time. Too slow forn = 10^5,m = 2 * 10^5, though ideal as a 10-line reference oracle on tiny random test graphs.
Follow-up questions
- Which algorithm would you switch to if directed edges could carry negative weights? Dijkstra's greedy guarantee breaks when negative edges exist because a node popped early could later be reached more cheaply by traveling down a large edge followed by a negative edge. Instead, use the Bellman-Ford algorithm—an
O(n * m)dynamic-programming pass that relaxes every edgen - 1times—and run onen-th check to detect reachable negative-weight cycles (where "shortest distance" is undefined because looping forever drives the cost to-infinity). If the graph is a directed acyclic graph (DAG)—a directed graph with zero cycles—you can sort the nodes in topological order (an ordering where every edgeu -> vhasubeforev) and relax edges in a singleO(n + m)pass even with negative weights. - How would you reconstruct the actual sequence of nodes along each shortest route instead of returning only the total cost? Maintain an array
parent = [-1] * n, and each timecandidate_distimprovesdist[neighbor], recordparent[neighbor] = node. For any target withdist[target] != -1, followcur = parent[cur]backward fromtargettosourceand reverse that list to obtain the forward path. Theparentarray addsO(n)space, though materializing full paths for allktargets could take up toO(k * n)output space if paths are long. - How can you eliminate the logarithmic heap overhead when every edge weight is a small positive integer bounded by W? You can replace the
O(log m)heap with 0-1 BFS (for weights{0, 1}using adeque) or Dial's algorithm—an array of buckets indexed by distance moduloW + 1—which drops thelog mheap factor and runs in linearO(n + m * W)time.
Follow-up questions
- Which algorithm would you switch to if directed edges could carry negative weights?
- How would you reconstruct the actual sequence of nodes along each shortest route instead of returning only the total cost?
- How can you eliminate the logarithmic heap overhead when every edge weight is a small positive integer bounded by W?
Similar questions
- 2D Max Pooling with Source Coordinates
- Smallest Parenthesized Target Expression
- Reach the Final Array Index
- Indexed Lookup in Run-Length Encoded String
- Minimum Driving Time Between Intersections
- 2D Max Pooling with Cell Indices
More Waymo interview questions
- Sensor Collection and Dispatch System for Mapping Fleets Medium
- Debounced Combobox Autocomplete with Async Cancellation Medium
- Comparing Sparse Incident Rates Across Unequal Mileage Medium Pro
- Fix Stale Views and RxJS Memory Leaks in Angular Medium Pro
- Validate Fleet Dispatch Readiness From Service Logs Medium Pro
- Presenting a Demanding Engineering Project and Its Core Obstacles Medium Pro
- Walk Through Your Proudest Engineering Project Medium Pro
- Map-Collection Vehicle Fleet and Ingestion Platform Hard Pro
- Worldwide Low-Latency Cache for Small Image Assets Medium Pro
- Design an Online Matchmaker with Cancellations and Timeouts Medium Pro