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 of targets, where index k gives the minimum cost of a directed walk from source to targets[k].
  • Reaching source from itself requires 0 edges and has cost 0.
  • Whenever no directed route leads from source to targets[k], record -1 at index k.

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 -> 1 with cost 2 + 3 = 5 (beating the direct edge 0 -> 1 of cost 9).
  • Best route to 3: 0 -> 2 -> 1 -> 3 with cost 2 + 3 + 4 = 9 (beating 0 -> 2 -> 3 of cost 2 + 11 = 13).
  • Best route to 4: 0 -> 2 -> 1 -> 3 -> 4 with cost 9 + 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 1 is the starting vertex (0).
  • Vertex 3 is reached along 1 -> 2 -> 3 with cost 6 + 4 = 10.
  • Link [0, 1, 3] points from 0 into 1 and cannot be traversed backward, so 0 is 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, cost 3 beats cost 8, and both occurrences of 3 in targets receive 3.
  • Vertices 4 and 0 have no incoming path from 2, so both receive -1.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • len(edges[i]) == 3
  • 0 <= u, v < n
  • 1 <= w <= 10^9
  • 0 <= source < n
  • 1 <= len(targets) <= n

Step-by-step walkthrough

  1. Understand the graph and the goal

    We have n nodes labeled 0 through n - 1 and a list of one-way roads edges[i] = [u, v, w], meaning you can travel from u to v (not v to u) at positive cost w >= 1. Given one starting node source and a list targets, we must return the shortest total distance from source to each node in targets, keeping the exact order of targets and returning -1 for 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 = 11
    

    Keep three details from the constraints in mind: - Graph size: Up to n = 10^5 nodes and m = 2 * 10^5 edges, so we need an O((n + m) log m) algorithm, not O(n * m). - Large distances: A chain of 10^5 edges of weight 10^9 reaches roughly 10^14. Python int values grow automatically without overflow (in C++ or Java you would need a 64-bit long 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.

  2. 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 1 via the single edge 0 -> 1 (distance 9) and misses the two-edge shortcut 0 -> 2 -> 1 (distance 5).
    • Bellman-Ford is too slow. Checking all m edges n - 1 times takes O(n * m) operations—up to 10^5 × 2 * 10^5 = 2 * 10^10 steps, which will time out.
    • Searching separately per target wastes work. targets can contain up to n entries. Running one single-source search from source computes the shortest distance to every node in the graph at once, answering all targets in a single pass.
  3. 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:

    1. Track dist[node], the shortest distance from source to node discovered so far (0 for source, -1 for unreached nodes).
    2. Repeatedly pick the unexpanded node with the smallest dist value and lock its distance in as final ("settle" it).
    3. Why is that node's distance guaranteed to be final? Any alternative path from source would 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's heapq cannot 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, check if current_dist > dist[node]: continue and skip it.

  4. Build an adjacency list

    Scanning the entire edges list every time we visit a node would be far too slow. Instead, we group outgoing edges by their starting node in an adjacency list, where graph[u] stores (neighbor, weight) for every edge u -> 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 graph
    

    If there are multiple parallel edges between u and v, we simply keep all of them in graph[u]—the cheapest one will naturally win when edges are checked.

  5. Code Dijkstra and answer the targets

    In dijkstra, storing -1 for unreached nodes keeps every entry an exact int (no float("inf") conversions) and matches the -1 output required for unreachable targets.

    Notice the strict inequality candidate_dist < dist[neighbor] when relaxing an edge: if two paths reach neighbor with 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 answers
    
  6. Trace Example 1 step by step

    Here is every heap pop on Example 1 (source = 0, dist starts 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] from dist = [0, 5, 2, 9, 11] returns [5, 9, 11].

  7. 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 n is the number of nodes and m is the number of edges. Building the adjacency list and dist array takes O(n + m) time; each node is expanded from the heap at most once, so each of the m edges triggers at most one heappush, giving at most m + 1 heap pushes and pops at O(log m) each; finally, looking up len(targets) answers (len(targets) <= n) takes O(len(targets)) time.
  • Space: O(n + m). The adjacency list stores n lists containing m (neighbor, weight) tuples in total, dist holds n integers, min_heap holds at most m + 1 pairs, and the output list holds len(targets) <= n integers.

Edge cases

  • source appears in targets: dist[source] starts at 0 and positive edge weights can never lower it, so it cleanly returns 0.
  • Unreachable nodes or empty edges: Unreached nodes keep their initial -1 value in dist.
  • Parallel edges between the same (u, v) pair: Keeping all of them in graph[u] works automatically because only the smallest current_dist + weight survives in dist[v].
  • Self-loops (u -> u) and directed cycles: Because every weight is at least 1, current_dist + weight around a self-loop or back to a settled node is strictly larger than its already-recorded dist and 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,999 edges of weight 10^9 totals roughly 10^14, which fits automatically in Python int (and requires 64-bit integers in statically typed languages).

Common mistakes

  • Using unweighted BFS: Minimizes hop count instead of total weight, returning 9 instead of 5 for node 1 in Example 1.
  • Marking nodes "visited" on push instead of settling on pop: Locks in the first path discovered to a node (0 -> 1 with cost 9) and blocks shorter multi-edge paths (0 -> 2 -> 1 with cost 5) 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 of node for every outdated heap copy and can time out on dense graphs.
  • Initializing dist with float("inf") and forgetting to translate back to -1: Causes unreachable targets to return inf instead of -1.

Alternative approaches

  • Early exit once all distinct targets are settled: Keep a remaining = set(targets) set and remove node when it is popped for the first time (current_dist == dist[node]); once remaining becomes empty, break out of the heap loop early. Worst-case complexity stays O(n + m log m) (for instance when a target is unreachable), but queries where all targets sit near source finish much sooner.
  • Bellman-Ford algorithm: Relaxes all m edges n - 1 times without a heap in O(n * m) time. Too slow for n = 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 edge n - 1 times—and run one n-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 edge u -> v has u before v) and relax edges in a single O(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 time candidate_dist improves dist[neighbor], record parent[neighbor] = node. For any target with dist[target] != -1, follow cur = parent[cur] backward from target to source and reverse that list to obtain the forward path. The parent array adds O(n) space, though materializing full paths for all k targets could take up to O(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 a deque) or Dial's algorithm—an array of buckets indexed by distance modulo W + 1—which drops the log m heap factor and runs in linear O(n + m * W) time.

Follow-up questions

Similar questions

More Waymo interview questions

All 90 Waymo questions →