Minimum Bottleneck Path in a Graph
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given an undirected graph on n vertices labeled 0 through n - 1 and a list of weighted bidirectional edges edges, compute the lowest possible bottleneck weight along any route from start to target:
def minimum_path_stress(
n: int,
edges: list[tuple[int, int, int]],
start: int,
target: int,
) -> int:
Each tuple (u, v, weight) in edges connects vertex u and vertex v in both directions with positive cost weight. Multiple parallel edges between the same vertex pair may occur, self-loops may appear, and the graph need not be connected.
The stress (or bottleneck) of a route is the maximum weight among the individual edges traversed on that route—not the sum of its edge weights.
- Return the smallest stress achievable over all valid routes from
starttotarget. - When
start == target, no edges need to be traversed, so return0. - When
targetcannot be reached fromstart, return-1.
Examples
Example 1
Input:
n = 6
edges = [(0, 1, 9), (0, 2, 2), (2, 3, 5), (3, 1, 4), (1, 4, 7), (3, 4, 11)]
start = 0
target = 4
Output: 7
Explanation: Taking the route 0 -> 2 -> 3 -> 1 -> 4 traverses weights 2, 5, 4, 7, whose heaviest edge is 7. Shorter-hop alternatives 0 -> 1 -> 4 (max 9) and 0 -> 2 -> 3 -> 4 (max 11) both incur higher peak weights, and no route reaches vertex 4 using only edges below 7.
Example 2
Input:
n = 4
edges = [(0, 1, 3), (2, 3, 5)]
start = 0
target = 3
Output: -1
Explanation: Vertices {0, 1} and {2, 3} belong to disconnected components, so no route connects 0 to 3.
Constraints
1 <= n <= 200,0000 <= len(edges) <= 300,0000 <= u, v < nand1 <= weight <= 10^9for each(u, v, weight)inedges0 <= start, target < n
Step-by-step walkthrough
Understand "path stress" vs. shortest-path distance
We are given an undirected graph with
nvertices (0ton - 1) and weighted edges(u, v, weight). For any path fromstarttotarget, its stress is the largest single edge weight along that path — not the sum of edge weights:weight 5 0 ----------- 1 Direct path 0 -> 1: | | sum = 5, stress = max(5) = 5 4 | | 4 | | Detour 0 -> 2 -> 3 -> 1: 2 ----------- 3 sum = 12, stress = max(4, 4, 4) = 4 <-- lower stress! weight 4Special rules from the statement: - If
start == target, no edges are needed, so return0. - Iftargetis unreachable fromstart, return-1. - Parallel edges (multiple edges between the same pair of vertices) and disconnected graphs are allowed. - With up ton = 200,000vertices and300,000edges, we need anO(E log E)algorithm.Turn "minimize the maximum" into an unlocking-roads sweep
Why are the first ideas we might try too slow? - Exploring every simple path with Depth-First Search (DFS) can visit exponentially many paths. - Testing every distinct edge weight
wby running a fresh Breadth-First Search (BFS) over edges withweight <= wtakesO(E * (V + E))time — tens of billions of steps whenE = 300,000.Notice, however, what happens as we gradually raise the allowed maximum weight
w: we only ever add edges, never remove them! Instead of restarting a graph search from scratch for every threshold, we can:- Sort all edges from lightest to heaviest.
- Start with
nisolated vertices and add edges one by one in sorted order, merging connected groups as we go. - Stop the very first moment
startandtargetbelong to the same connected group, and return the weightwof the edge we just added!
Why is that guaranteed to be optimal? - Achievable (
<= w): Every edge added so far has weight at mostw, andstartcan now reachtargetusing a subset of those edges. - Minimal (>= w): Every edge strictly lighter thanwcame earlier in sorted order and was already added, yetstartandtargetwere still in separate groups before this step.(If you have seen Kruskal's minimum spanning tree algorithm, this is the exact same light-to-heavy sweep, stopped as soon as
startandtargetconnect!)Track connected groups with Union-Find
To merge groups and check whether two vertices share a group in nearly
O(1)time, we use a Union-Find (also called Disjoint Set Union):- Each group is represented as a small rooted tree using an array
parent, whereparent[v]points one step upward toward the group's leader (root), and a root points to itself (parent[root] == root). - Two vertices are in the same connected group if and only if they have the same root.
- Whenever
find_root(parent, node)walks up to findroot, a second loop rewires every visited vertex along the chain to point directly atroot. This optimization is called path compression, and it makes future lookups on those vertices instant:
Before find_root(3): After path compression: 0 (root) 0 (root) | / | \ 1 1 2 3 | 2 | 3We write
find_rootwith plainwhileloops rather than recursion so a deep chain can never hit Python's default1000-call recursion limit.def find_root(parent: List[int], node: int) -> int: """Return the root representative of `node`'s component using path compression.""" # Pass 1: Walk parent pointers upward until we reach a root (a node pointing to itself). root = node while parent[root] != root: root = parent[root] # Pass 2 (Path compression): Point every visited node directly at `root` # so future lookups on this path finish in O(1) steps. curr = node while parent[curr] != root: next_parent = parent[curr] parent[curr] = root curr = next_parent return root- Each group is represented as a small rooted tree using an array
Merge groups with union by size and stop at the first connection
When an edge
(u, v, weight)connects two different groups (root_u != root_v), we merge them using union by size: we track each group's vertex count incomp_size[root]and always attach the smaller group's root under the larger group's root. Because a vertex's tree only gains a level above it when its group at least doubles in size, tree height stays at mostlog2(n)even before path compression!Watch out for three clean details in
minimum_path_stress: 1. Checkstart == targetfirst: An empty path uses zero edges (0stress), even if the graph has zero edges. 2. Pack(weight, u, v)tuples: Puttingweightfirst lets Python's built-in.sort()order edges from lightest to heaviest directly. 3. Skiproot_u == root_v: Self-loops (u == v) and heavier parallel or cycle edges whose endpoints are already connected do not change connectivity, so we skip them and only checkfind_root(parent, start) == find_root(parent, target)right after a real merge.def minimum_path_stress( n: int, edges: list[tuple[int, int, int]], start: int, target: int, ) -> int: if start == target: return 0 edges_by_weight: List[Tuple[int, int, int]] = [] for u, v, weight in edges: edges_by_weight.append((weight, u, v)) edges_by_weight.sort() parent = list(range(n)) comp_size = [1] * n for weight, u, v in edges_by_weight: root_u = find_root(parent, u) root_v = find_root(parent, v) if root_u == root_v: continue if comp_size[root_u] < comp_size[root_v]: root_u, root_v = root_v, root_u parent[root_v] = root_u comp_size[root_u] += comp_size[root_v] if find_root(parent, start) == find_root(parent, target): return weight return -1Trace Example 1 step by step
Example 1 has
n = 6,start = 0,target = 4, andedges = [(0, 1, 9), (0, 2, 2), (2, 3, 5), (3, 1, 4), (1, 4, 7), (3, 4, 11)].Sorted edges_by_weight: 1. (w=2, 0--2) groups: {0, 2}, {1}, {3}, {4}, {5} -> root(0) != root(4), keep going 2. (w=4, 3--1) groups: {0, 2}, {1, 3}, {4}, {5} -> root(0) != root(4), keep going 3. (w=5, 2--3) groups: {0, 1, 2, 3}, {4}, {5} -> root(0) != root(4), keep going 4. (w=7, 1--4) groups: {0, 1, 2, 3, 4}, {5} -> root(0) == root(4) -> return 7! 5. (w=9, 0--1) (never reached) 6. (w=11, 3--4) (never reached)At weight
7, vertices0and4land in the same group{0, 1, 2, 3, 4}via the path0 -> 2 -> 3 -> 1 -> 4(weights2, 5, 4, 7), and we immediately return7without even inspecting the heavier edges9and11.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_root(parent: List[int], node: int) -> int: """Return the root representative of `node`'s component using path compression.""" # Pass 1: Walk parent pointers upward until we reach a root (a node pointing to itself). root = node while parent[root] != root: root = parent[root] # Pass 2 (Path compression): Point every visited node directly at `root` # so future lookups on this path finish in O(1) steps. Uses loops, not recursion, # to avoid Python's 1000-frame recursion limit on large graphs. curr = node while parent[curr] != root: next_parent = parent[curr] parent[curr] = root curr = next_parent return root def minimum_path_stress( n: int, edges: list[tuple[int, int, int]], start: int, target: int, ) -> int: # Base case: an empty path from a vertex to itself uses zero edges, so its stress is 0. if start == target: return 0 # Phase 1: Reorder each edge as (weight, u, v) and sort ascending by weight # so we unlock edges from lightest to heaviest. edges_by_weight: List[Tuple[int, int, int]] = [] for u, v, weight in edges: edges_by_weight.append((weight, u, v)) edges_by_weight.sort() # Phase 2: Initialize Union-Find over vertices 0 .. n-1. # parent[v]: parent pointer in v's component tree (root satisfies parent[r] == r) # comp_size[r]: number of vertices in root r's connected component parent = list(range(n)) comp_size = [1] * n # Phase 3: Add edges from lightest to heaviest (Kruskal-style sweep). # The very first edge whose union puts `start` and `target` in the same component # gives the minimum possible maximum edge weight on any start-to-target path. for weight, u, v in edges_by_weight: root_u = find_root(parent, u) root_v = find_root(parent, v) if root_u == root_v: # Self-loops and heavier parallel/cycle edges inside one component change nothing. continue # Union by size: attach the smaller tree under the larger tree to keep height <= log2(n). if comp_size[root_u] < comp_size[root_v]: root_u, root_v = root_v, root_u parent[root_v] = root_u comp_size[root_u] += comp_size[root_v] # Connectivity only changes right after merging two distinct components. if find_root(parent, start) == find_root(parent, target): return weight # Every edge was added and `start` still cannot reach `target`. return -1✅ Submit now — all tests should pass.
Intuition & how it works
Picture the vertices as mountain towns and each edge's weight as the elevation of the pass connecting two towns. You want to travel from start to target while keeping the highest pass you cross as low as possible. Imagine starting an altitude ceiling at 0 and raising it gradually so passes unlock from lowest elevation to highest: at first every town sits alone, then unlocked passes merge towns into larger connected components (groups of vertices that can all reach one another), and the very first moment start and target end up in the same component, the pass you just unlocked is guaranteed to be the lowest possible peak elevation!
Why do obvious approaches fall short? Running standard shortest-path Dijkstra on the sum of weights picks a single direct edge of weight 5 over a three-edge detour of weights 4, 4, 4 (sum = 12), even though the detour has smaller stress (4 < 5). Trying every simple path via Depth-First Search blows up exponentially, and running a fresh Breadth-First Search for every distinct edge weight takes O(E * (V + E)) time — tens of billions of steps when n = 200,000.
To track merging components without re-searching the graph, we use Union-Find (also called Disjoint Set Union, an array-based forest that merges groups and checks whether two vertices share a group in near-constant time using path compression — pointing visited nodes straight to their group's root — and union by size — attaching the smaller group under the larger one). Here is Example 1 (start = 0, target = 4) after sorting edges by weight:
Start: {0}, {1}, {2}, {3}, {4}, {5}
Add (0--2, w=2) -> {0, 2}, {1}, {3}, {4}, {5} (0 and 4 still apart)
Add (3--1, w=4) -> {0, 2}, {1, 3}, {4}, {5} (0 and 4 still apart)
Add (2--3, w=5) -> {0, 1, 2, 3}, {4}, {5} (0 and 4 still apart)
Add (1--4, w=7) -> {0, 1, 2, 3, 4}, {5} (0 and 4 connected! Return 7)
Complexity
Let V = n be the number of vertices and E = len(edges) be the number of edges.
- Time:
O(V + E log E). Building and sortingedges_by_weighttakesO(E log E)comparisons, initializingparentandcomp_sizetakesO(V), and processing up toEedges with Union-Find (using both path compression and union by size) takesO(E * α(V)), whereα(V)is the inverse Ackermann function (an extraordinarily slow-growing function that stays<= 4for every input size that fits in memory). - Space:
O(V + E). Storing theparentandcomp_sizearrays takesO(V)integers, and storing the sortededges_by_weightcopy takesO(E)tuples.
Edge cases
start == target: Handled immediately at the top by returning0, even whenedgesis completely empty (n = 1, edges = []).- Disconnected
startandtarget(oredges = []withstart != target): All edges are processed withoutstartandtargetever sharing a root, so the function returns-1. - Parallel edges between the same vertices: Sorting visits the lightest copy first; any heavier copies arrive when
root_u == root_vis already true and are skipped. - Self-loops (
u == v):root_u == root_vholds immediately, so self-loops are ignored without affecting components. - Multiple edges tied at the optimal weight: Even if two tied edges of weight
wmust both be added beforestartandtargetconnect, the second merge still returnsw, and no strictly lighter set of edges was enough. - Large weights up to
10^9: Edge weights are only compared, never summed, avoiding any risk of integer overflow even in fixed-width languages.
Common mistakes
- Minimizing the sum of weights instead of the maximum weight: Standard Dijkstra relaxes with
dist[u] + weightinstead ofmax(stress[u], weight), choosing shorter sums with heavier individual edges. - Forgetting the
start == targetcheck before the edge loop: Because the loop only checks connectivity after merging two distinct vertices,start == targetwith no incident edges would fall through and wrongly return-1. - Running Kruskal's algorithm to completion: Returning the heaviest edge in the entire spanning forest instead of stopping as soon as
startandtargetconnect can include an unrelated heavy edge in another part of the graph. - Checking
root_u == find_root(parent, target)instead of comparingstartandtarget: An edge(u, v)might bridge two middle components — one containingstartand one containingtarget— withoutuorvbeingstartortargetdirectly. Always testfind_root(parent, start) == find_root(parent, target). - Writing recursive
find_rootwithout union by size: Without balancing tree sizes, an adversarial edge order can build a chain of depth200,000and crash withRecursionError.
Alternative approaches
- Minimax Dijkstra (priority-queue search): Track
best_stress[v](the smallest path stress found so far to reachv) and push(stress, v)onto a min-heap (a binary tree array that always pops the smallest stress next), relaxing neighbors vianew_stress = max(stress, weight). Becausemax(stress, weight) >= stress, stress never decreases along a path, so the first timetargetis popped from the heap its stress is optimal inO((V + E) log V)time. This also works directly on directed graphs. - Binary search on the answer + BFS: Sort the unique edge weights (
<= Ecandidates) and binary search for the smallest weightwwhere a BFS traversing only edges withweight <= wreachestarget. Easy to reason about, running inO((V + E) log E)time across roughlylog2(300,000) ≈ 19BFS traversals.
Follow-up questions
- How would you preprocess a static graph so you can answer Q independent (start, target) bottleneck queries quickly? Build a minimum spanning forest (the set of edges actually accepted by a full Kruskal sweep across the graph, taking
O(E log E)time once) — a classic graph property guarantees that the unique tree path between any two connected vertices in this forest achieves their minimum possible maximum edge! Root each tree and precompute binary lifting tables (up[k][v]storing the2^k-th ancestor ofvandmax_edge[k][v]storing the heaviest edge on that2^k-step jump) inO(V log V)time and space, which then answers every(start, target)query inO(log V)time. - If the caller also needs the actual sequence of vertices along an optimal route rather than just the bottleneck value, how would you recover it? Keep the exact edges accepted during our Kruskal sweep until
startandtargetconnect (at mostV - 1edges, all with weight<= answer). Build an adjacency list from just those accepted edges and run a singleO(V)BFS fromstarttotarget, recordingcame_from[neighbor] = currso you can walk backward fromtargettostartand reverse the list. - How does the algorithm change if edges are directed one-way links instead of undirected roads? Union-Find can no longer be used because reachability in a directed graph is not symmetric (
ureachingvdoes not meanvreachesu). Instead, build a directed adjacency listadj[u] = [(v, weight), ...]and run the minimax Dijkstra algorithm (new_stress = max(curr_stress, weight)) inO((V + E) log V)time, or binary search over the sorted edge weights with a directed BFS check inO((V + E) log E)time.
Follow-up questions
- How would you preprocess a static graph so you can answer Q independent (start, target) bottleneck queries quickly?
- If the caller also needs the actual sequence of vertices along an optimal route rather than just the bottleneck value, how would you recover it?
- How does the algorithm change if edges are directed one-way links instead of undirected roads?
Similar questions
- Validate Properly Nested Bracket Delimiters
- Days Needed for Pesticide Row to Stabilize
- Minimum Conference Rooms Needed
- Counting Distinct Coin Combinations
- Earliest Unique Character Index
- Matching Index Pairs in Sorted Arrays
More Walmart Labs interview questions
- Two Sum With Lexicographic Index Tie-Breaking Medium
- Leadership Scenarios on Persuasion, Data, Outages, and Ethics Medium
- Navigating Setbacks and Small Talk in a Hiring Manager Chat Medium Pro
- High-Throughput Multi-Seller E-Commerce Catalog Architecture Medium Pro
- Grounded Multi-Turn Agentic Search System Easy Pro
- Dynamic Half-Open Interval Coverage Tracker Hard Pro
- Cross-Team Technical Disagreement and Execution Alignment Easy Pro
- Shortest All-Talent Subarray From Each Start Hard Pro
- Spring Boot & Thymeleaf Multi-Page Form Architecture Medium Pro
- Validate Properly Nested Bracket Delimiters Medium Pro