Fastest Route Time Through a One-Way Street Network
Trees & GraphsAuto-graded · 23 test casesLast 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
sourceandtargetare the same junction, the answer is0. - If
targetcannot be reached fromsource, return-1. - A junction may have no outgoing streets (its list is empty).
- Streets with a driving time of
0are 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, whereN = len(road_map).- The total number of streets
Eis at most100,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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a single-source shortest path problem on a directed graph with non-negative weights, which is the classic use case for Dijkstra's algorithm.
- If
source == target, return0right away. - Keep an array
bestholding the smallest known time to reach each junction. Initialize every entry to infinity, exceptbest[source] = 0. - Keep a min-heap of
(time, junction)pairs, starting with(0, source). - Repeatedly pop the pair with the smallest time.
- If its time differs from
best[junction], it is a stale entry (a better route was found after it was pushed), so skip it. - If the junction is
target, return its time. It is final. - Otherwise, for each street
[v, minutes]out of the junction, computetime + minutes. If this is strictly smaller thanbest[v], updatebest[v]and push the new pair.
- If its time differs from
- If the heap empties without popping
target, return-1.
Python's heapq cannot decrease a key, so we push duplicates and discard outdated ones when they are popped (lazy deletion).
Why it is correct
When a junction is popped with an up-to-date time d, that time is the true shortest time. Suppose a shorter route existed. Along it, consider the first junction not yet finalized. Its predecessor on that route was finalized, so the street into it was already relaxed, and the heap holds that junction with a time no larger than the prefix length of the route. Since weights are non-negative, this prefix is at most the length of the whole shorter route, which is less than d. That junction would then have been popped before ours, a contradiction. So the first pop of target gives the optimal answer. Zero-weight streets only create ties and never break this argument. Cycles and parallel streets are handled by the strict < check, and a drained heap means the target is unreachable.
Complexity
- Time:
O((N + E) log E), since each successful relaxation pushes one heap entry and each push or pop costsO(log E). - Space:
O(N + E)for the best-time array and the heap, which can hold up to one entry per successful relaxation.
Reference solution
import heapq
from typing import List
def fastest_route_time(road_map: List[List[List[int]]], source: int, target: int) -> int:
if source == target:
return 0
n = len(road_map)
best = [float('inf')] * n
best[source] = 0
heap = [(0, source)]
while heap:
time_so_far, node = heapq.heappop(heap)
if time_so_far != best[node]:
continue
if node == target:
return time_so_far
for nxt, minutes in road_map[node]:
candidate = time_so_far + minutes
if candidate < best[nxt]:
best[nxt] = candidate
heapq.heappush(heap, (candidate, nxt))
return -1