KatInterview

Compute Minimum Distances to Multiple Destinations

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsshortest-pathdijkstragraph-traversal

Last 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^5
  • 0 <= edges.length <= 2 * 10^5
  • edges[i].length == 3
  • 0 <= u, v < n
  • 1 <= w <= 10^9
  • 0 <= start < n
  • 1 <= destinations.length <= n
  • 0 <= 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.