Find Shortest Paths to Target Nodes
WaymoSoftware Engineer · Technical ScreenLast updated
This question evaluates knowledge of graph algorithms and algorithmic problem-solving, specifically computing shortest paths in weighted directed graphs and handling unreachable targets.
You are given a weighted directed graph representing distances between nodes.
- There are
nnodes labeled from0ton - 1. edges[i] = [u, v, w]means there is a directed edge from nodeuto nodevwith positive distancew.- You are given a starting node
source. - You are also given a list of target nodes
targets.
Return the shortest distance from source to each target node. If a target cannot be reached from source, return -1 for that target.
The result should preserve the order of targets.
Example:
n = 5
edges = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5], [3, 4, 3]]
source = 0
targets = [1, 3, 4]
Output:
[3, 4, 7]
Explanation:
- The shortest path from
0to1is0 -> 2 -> 1, with distance1 + 2 = 3. - The shortest path from
0to3is0 -> 2 -> 1 -> 3, with distance1 + 2 + 1 = 4. - The shortest path from
0to4is0 -> 2 -> 1 -> 3 -> 4, with distance1 + 2 + 1 + 3 = 7.
Constraints:
1 <= n <= 10^50 <= edges.length <= 2 * 10^5edges[i].length == 30 <= u, v < n1 <= w <= 10^90 <= source < n1 <= targets.length <= n- All edge weights are positive.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.