Compute Minimum Distances to Multiple Destinations
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests understanding of single-source shortest path algorithms on weighted directed graphs with positive edge weights.
You're given a weighted directed graph with n nodes numbered 0 through n - 1.
The graph is defined by an edge list where edges[i] = [u, v, w] represents a directed edge going from node u to node v with a positive weight w.
Given a starting node start and a list of destination nodes destinations, compute the minimum distance from start to each destination node.
For any destination that cannot be reached from the starting node, return -1 for that destination.
Your answer must preserve the original order of the destinations list.
Constraints:
1 <= n <= 10^50 <= edges.length <= 2 * 10^5edges[i].length == 30 <= u, v < n1 <= w <= 10^90 <= start < n1 <= destinations.length <= n0 <= destinations[i] < n- All edge weights are positive integers
Examples
Example 1
Input: min_distances_to_destinations(5, [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5], [3, 4, 3]], 0, [1, 3, 4])
Output: [3, 4, 7]
Example 2
Input: min_distances_to_destinations(4, [[0, 1, 5], [1, 2, 2]], 0, [0, 2, 3])
Output: [0, 7, -1]
Example 3
Input: min_distances_to_destinations(6, [[0, 1, 2], [0, 1, 7], [1, 2, 3], [2, 0, 1], [3, 4, 1]], 3, [4, 0, 5])
Output: [1, -1, -1]
Hints
Hint 1
This is a single-source shortest path problem with positive weights—what classic algorithm fits this scenario?
Hint 2
Running one graph traversal from the start node is more efficient than running separate searches for each destination.
Hint 3
A min-heap can help you always process the node with the smallest tentative distance first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding the shortest path from a single source to multiple destinations in a weighted directed graph with positive edge weights. Dijkstra's algorithm is the ideal choice for this scenario.
The strategy is to run Dijkstra's algorithm once from the starting node to compute the minimum distance to all reachable nodes. Then look up the distance for each requested destination.
Algorithm steps:
-
Build an adjacency list representation of the graph where
graph[u]contains tuples(v, w)for each outgoing edge fromutovwith weightw. -
Initialize a distance array where
distances[start] = 0and all other nodes have distance infinity. -
Use a min-heap to track nodes to process, prioritized by their tentative distance. Start with
(0, start)in the heap. -
Process nodes in order of increasing distance: Pop the node with minimum distance from the heap. For each neighbor, check if going through the current node offers a shorter path. If so, update the neighbor's distance and add it to the heap.
-
Handle duplicate heap entries: Since Python's heapq doesn't support updating priorities, a node may appear multiple times in the heap with different distances. When popping a node, check if the popped distance matches the recorded best distance—if not, skip it as outdated.
-
Collect results: For each destination, return its final distance, or
-1if it remains at infinity (unreachable).
Why It Works
Dijkstra's algorithm maintains this invariant: when a node is popped from the heap with a distance matching its recorded best, that distance is optimal and final.
This holds because all edge weights are positive. Any alternative path to that node must pass through some unfinalized node, which already has a distance at least as large. Adding positive weights can only increase the total, so no future discovery can improve it.
Unreachable nodes are never added to the heap and retain their infinity distance, which we convert to -1 in the output.
Complexity
-
Time: O((V + E) log E) where V = n and E = len(edges). Building the graph takes O(V + E). Each edge relaxation can trigger a heap push, giving at most E heap operations, each taking O(log E) time.
-
Space: O(V + E) for the adjacency list, distance array, and heap storage.
Solution Code
import heapq
from typing import List
def min_distances_to_destinations(n: int, edges: List[List[int]], start: int, destinations: List[int]) -> List[int]:
# Build adjacency list for directed graph
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
# Initialize distance tracking
distances = [float("inf")] * n
distances[start] = 0
heap = [(0, start)]
# Dijkstra's algorithm
while heap:
current_dist, node = heapq.heappop(heap)
# Skip outdated entries
if current_dist != distances[node]:
continue
# Relax neighbors
for neighbor, weight in graph[node]:
new_dist = current_dist + weight
if new_dist < distances[neighbor]:
distances[neighbor] = new_dist
heapq.heappush(heap, (new_dist, neighbor))
# Return results for requested destinations
return [-1 if distances[dest] == float("inf") else distances[dest] for dest in destinations]