Bottleneck Path Under an Edge-Weight Cap
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests whether a candidate can find the minimax-cost path in a filtered graph, recognising that one edge attribute gates inclusion while another drives the optimisation.
Problem
You are given a pipeline network of n stations numbered 0 through n - 1. Stations are connected by bidirectional pipes. Each pipe is described by four integers [a, b, delay, risk]:
aandbare the two stations it connects.delayis the time it takes to transfer data through the pipe.riskis the hazard rating of the pipe.
You are also given a starting station src, a target station dst, and an integer max_delay representing the maximum acceptable transfer delay for any single pipe.
A pipe may only be used if its delay is at most max_delay.
The hazard of an entire route is defined as the highest risk value among all pipes used on that route. Your goal is to find a route from src to dst, using only pipes that satisfy the delay constraint, that minimises this hazard.
Return the minimum possible hazard for any such route. If src == dst, return 0. If no valid route exists, return -1.
Constraints
1 <= n <= 10^50 <= len(edges) <= 2 * 10^5- Each edge is
[a, b, delay, risk]where0 <= a, b < nanda != b 0 <= delay, risk, max_delay <= 10^90 <= src, dst < n- Multiple pipes between the same pair of stations are allowed
Examples
Example 1
Input: min_required_safety(4, [[0, 1, 10, 5], [1, 2, 8, 9], [0, 2, 15, 7], [2, 3, 5, 4]], 0, 3, 12)
Output: 9
Example 2
Input: min_required_safety(3, [[0, 1, 5, 8], [1, 2, 6, 7]], 0, 2, 4)
Output: -1
Hints
Hint 1
Start by throwing away every pipe whose delay exceeds max_delay — those pipes simply don't exist for this problem. What kind of graph search works on what remains?
Hint 2
The cost of a route is the maximum risk along it, not a sum. Think about how you would adapt Dijkstra's relaxation step: instead of dist[u] + w, what expression gives the cost of extending a path through a new pipe?
Hint 3
A min-heap lets you pop the node with the smallest bottleneck cost first. When the destination is popped, you already have the answer — but this early-exit guarantee only holds with a priority queue, not a plain FIFO queue.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Separating the two constraints
The two pipe attributes play completely different roles.
delay is a hard filter: a pipe is either usable (delay <= max_latency) or it isn't. Build the adjacency list with only the pipes that pass this filter and ignore the rest entirely.
risk is a bottleneck cost: the cost of a route is the single highest risk value along it, not a sum. The goal is to minimise this maximum — a classic minimax (bottleneck) path problem.
Why Dijkstra still works
Standard Dijkstra relaxes edges with dist[u] + weight. Here the relaxation becomes max(cost_so_far, risk). This substitution is valid because the cost function still satisfies the two properties Dijkstra needs:
- Monotone: extending a path with
maxnever lowers the cost. - Order-preserving: if
a <= bthenmax(a, r) <= max(b, r)for anyr.
Because of these properties, the first time a node is popped from the min-heap its recorded cost is already the global minimum bottleneck to reach it. Any alternative path to that node that hasn't been explored yet must leave the settled region through a node with an equal or larger cost, and max can only keep it the same or increase it further. So the early exit when the destination is popped is correct.
Why a plain FIFO queue is not sufficient. A FIFO queue does not process nodes in cost order. The destination might be reached cheaply via a long multi-hop route, but a single expensive direct pipe could reach it first in queue order. Without the heap's ordering guarantee, the early exit can return a stale, suboptimal value. The FIFO approach is only safe if you remove the early exit and always run to completion, which forfeits the performance benefit.
Edge cases
source == destination: return0immediately — no pipes need to be traversed.- All pipes filtered out, or graph is disconnected: the heap empties without the destination being settled; return
-1. delay == max_latency: the pipe is allowed (<=).risk == 0: zero is a valid bottleneck cost. UseINF(notNoneor0) to mark unvisited nodes.- Parallel pipes between the same pair of stations: both enter the adjacency list; the heap naturally picks the one with lower risk.
Complexity
- Time:
O(E log E)— filtering edges isO(E), and the Dijkstra phase processes each edge at most twice (once per direction) and each heap push isO(log E). SinceE <= V^2, this is equivalent toO(E log V). - Space:
O(V + E)for the adjacency list, thebestarray, and the heap.
With n = 10^5 and |edges| = 2 * 10^5 this runs comfortably within typical time limits in Python.
Alternative: Kruskal-style sweep with Union-Find
Sort the allowed pipes by risk. Merge their endpoints into a Union-Find structure in that order. The answer is the risk of the first pipe whose merge connects source and destination. This is correct because the minimax path always exists on a minimum spanning tree. The complexity is the same: O(E log E) for sorting plus near-linear Union-Find operations.
import heapq
from typing import List
def min_required_safety(n: int, edges: List[List[int]], source: int, destination: int, max_latency: int) -> int:
if source == destination:
return 0
# Build a filtered adjacency list: only pipes within the delay budget.
graph = [[] for _ in range(n)]
for a, b, delay, risk in edges:
if delay <= max_latency:
graph[a].append((b, risk))
graph[b].append((a, risk))
INF = float("inf")
best = [INF] * n # best (lowest) bottleneck cost reaching each station
best[source] = 0
heap = [(0, source)] # (bottleneck so far, station)
while heap:
cost, node = heapq.heappop(heap)
if cost > best[node]:
continue # stale entry — a better path was already found
if node == destination:
return cost # min-heap guarantees this is optimal
for neighbour, risk in graph[node]:
candidate = max(cost, risk)
if candidate < best[neighbour]:
best[neighbour] = candidate
heapq.heappush(heap, (candidate, neighbour))
return -1