KatInterview

Shortcut by Adding Free Unit Edges

Trees & GraphsAuto-graded · 18 test cases
EasyAuto-gradedTrees & Graphsgraphsshortest-pathreasoning

Last updated

Reason about degrees of freedom: since you may add arbitrary weight-1 edges, the optimal distance collapses to a constant.

You have a directed graph whose vertices are numbered 1 through n. It comes with a list of existing directed edges, each carrying a positive integer weight. The edges are given as three parallel arrays of the same length m: from_nodes[i] is the tail of edge i, to_nodes[i] is its head, and weights[i] is its weight.

Beyond these edges, you are permitted to insert as many extra directed edges as you like. Every extra edge has weight exactly 1, and you may connect any ordered pair of vertices — the endpoints and the count are entirely your choice (including zero edges).

Your goal is to make the shortest-path distance from vertex 1 to vertex n as small as possible. Return that minimum achievable distance.

Notes on the boundary behavior:

  • If n == 1, the source and the destination coincide, so the empty path already has length 0. Since all edge weights are positive, nothing can reduce it further.
  • Otherwise a path from 1 to n must use at least one edge, and every edge (existing or added) has weight at least 1.

Constraints

  • 1 <= n <= 2 * 10^5
  • 1 <= m <= 2 * 10^5
  • 1 <= from_nodes[i], to_nodes[i] <= n
  • 1 <= weights[i] <= 10^9
  • The three edge arrays always have equal length m.

Examples

Example 1

Input: best_reachable_distance(1, [1], [1], [7])

Output: 0

Example 2

Input: best_reachable_distance(2, [1], [2], [100])

Output: 1

Example 3

Input: best_reachable_distance(5, [1, 2, 3], [2, 3, 5], [10, 20, 30])

Output: 1

Example 4

Input: best_reachable_distance(4, [1, 1, 2, 3], [2, 3, 4, 4], [9, 1, 1, 50])

Output: 1

Hints

Hint 1

Before writing Dijkstra, ask what the freedom to add edges actually buys you — can you connect the source straight to the destination?

Hint 2

A single added edge from vertex 1 to vertex n costs 1. Can anything ever cost less than that when the two vertices differ?

Hint 3

Think separately about the case where the source and the destination are the same vertex.