KatInterview

Fastest Route Time Through a One-Way Street Network

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsdijkstrashortest-pathgraph

Last updated

Find the minimum total cost between two nodes of a directed graph with non-negative edge weights, returning -1 if no route exists. Tests shortest-path reasoning with a priority queue.

Fastest Route Time Through a One-Way Street Network

A city's streets are modeled as a directed graph. Each node is a junction numbered 0 to N-1, and each directed edge is a one-way street with a driving time in minutes.

The graph is given as a list indexed by junction id. For each junction u, road_map[u] is a list of [v, minutes] pairs. Each pair describes a one-way street from u to v that takes minutes minutes to drive. The number of junctions is len(road_map).

Given a departure junction source and an arrival junction target, return the smallest total number of minutes needed to drive from source to target, following streets only in their allowed direction.

Rules

  • The total time of a route is the sum of the driving times of the streets it uses.
  • If source and target are the same junction, the answer is 0.
  • If target cannot be reached from source, return -1.
  • A junction may have no outgoing streets (its list is empty).
  • Streets with a driving time of 0 are allowed.
  • Several streets may connect the same pair of junctions, and the graph may contain cycles or several disconnected parts. Your solution must handle all of these.

Constraints

  • 1 <= N <= 10,000, where N = len(road_map).
  • The total number of streets E is at most 100,000.
  • Every driving time is an integer with minutes >= 0.
  • 0 <= source, target < N.

Examples

Example 1

Input: fastest_route_time([[[1, 5], [2, 1]], [[3, 2]], [[1, 1], [3, 7]], []], 0, 3)

Output: 4

Example 2

Input: fastest_route_time([[[1, 10]], [[2, 5]], [], []], 0, 3)

Output: -1

Example 3

Input: fastest_route_time([[[1, 0]], []], 0, 0)

Output: 0

Hints

Hint 1

Because every driving time is non-negative, a greedy strategy that always expands the closest not-yet-finalized junction works. Think about which data structure gives you that junction quickly.

Hint 2

Keep a best-known time for each junction, initialized to infinity except for the source at 0. Use a min-heap of (time, junction) and relax each outgoing street when you pop a junction.

Hint 3

A heap has no decrease-key, so push a new entry whenever you improve a time and skip popped entries whose time no longer matches the best-known value. Return as soon as the target is popped, and return -1 if the heap empties first.