Katkat

Find Shortest Paths to Target Nodes

WaymoSoftware Engineer · Technical Screen

Last 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 n nodes labeled from 0 to n - 1.
  • edges[i] = [u, v, w] means there is a directed edge from node u to node v with positive distance w.
  • 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 0 to 1 is 0 -> 2 -> 1, with distance 1 + 2 = 3.
  • The shortest path from 0 to 3 is 0 -> 2 -> 1 -> 3, with distance 1 + 2 + 1 = 4.
  • The shortest path from 0 to 4 is 0 -> 2 -> 1 -> 3 -> 4, with distance 1 + 2 + 1 + 3 = 7.

Constraints:

  • 1 <= n <= 10^5
  • 0 <= edges.length <= 2 * 10^5
  • edges[i].length == 3
  • 0 <= u, v < n
  • 1 <= w <= 10^9
  • 0 <= source < n
  • 1 <= targets.length <= n
  • All edge weights are positive.