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 start to target.
  • When start == target, no edges need to be traversed, so return 0.
  • When target cannot be reached from start, 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,000
  • 0 <= len(edges) <= 300,000
  • 0 <= u, v < n and 1 <= weight <= 10^9 for each (u, v, weight) in edges
  • 0 <= start, target < n

Step-by-step walkthrough

  1. Understand "path stress" vs. shortest-path distance

    We are given an undirected graph with n vertices (0 to n - 1) and weighted edges (u, v, weight). For any path from start to target, 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 4
    

    Special rules from the statement: - If start == target, no edges are needed, so return 0. - If target is unreachable from start, return -1. - Parallel edges (multiple edges between the same pair of vertices) and disconnected graphs are allowed. - With up to n = 200,000 vertices and 300,000 edges, we need an O(E log E) algorithm.

  2. 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 w by running a fresh Breadth-First Search (BFS) over edges with weight <= w takes O(E * (V + E)) time — tens of billions of steps when E = 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:

    1. Sort all edges from lightest to heaviest.
    2. Start with n isolated vertices and add edges one by one in sorted order, merging connected groups as we go.
    3. Stop the very first moment start and target belong to the same connected group, and return the weight w of the edge we just added!

    Why is that guaranteed to be optimal? - Achievable (<= w): Every edge added so far has weight at most w, and start can now reach target using a subset of those edges. - Minimal (>= w): Every edge strictly lighter than w came earlier in sorted order and was already added, yet start and target were 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 start and target connect!)

  3. 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, where parent[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 find root, a second loop rewires every visited vertex along the chain to point directly at root. 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
          |
          3
    

    We write find_root with plain while loops rather than recursion so a deep chain can never hit Python's default 1000-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
    
  4. 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 in comp_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 most log2(n) even before path compression!

    Watch out for three clean details in minimum_path_stress: 1. Check start == target first: An empty path uses zero edges (0 stress), even if the graph has zero edges. 2. Pack (weight, u, v) tuples: Putting weight first lets Python's built-in .sort() order edges from lightest to heaviest directly. 3. Skip root_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 check find_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 -1
    
  5. Trace Example 1 step by step

    Example 1 has n = 6, start = 0, target = 4, and edges = [(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, vertices 0 and 4 land in the same group {0, 1, 2, 3, 4} via the path 0 -> 2 -> 3 -> 1 -> 4 (weights 2, 5, 4, 7), and we immediately return 7 without even inspecting the heavier edges 9 and 11.

  6. 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 sorting edges_by_weight takes O(E log E) comparisons, initializing parent and comp_size takes O(V), and processing up to E edges with Union-Find (using both path compression and union by size) takes O(E * α(V)), where α(V) is the inverse Ackermann function (an extraordinarily slow-growing function that stays <= 4 for every input size that fits in memory).
  • Space: O(V + E). Storing the parent and comp_size arrays takes O(V) integers, and storing the sorted edges_by_weight copy takes O(E) tuples.

Edge cases

  • start == target: Handled immediately at the top by returning 0, even when edges is completely empty (n = 1, edges = []).
  • Disconnected start and target (or edges = [] with start != target): All edges are processed without start and target ever 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_v is already true and are skipped.
  • Self-loops (u == v): root_u == root_v holds immediately, so self-loops are ignored without affecting components.
  • Multiple edges tied at the optimal weight: Even if two tied edges of weight w must both be added before start and target connect, the second merge still returns w, 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] + weight instead of max(stress[u], weight), choosing shorter sums with heavier individual edges.
  • Forgetting the start == target check before the edge loop: Because the loop only checks connectivity after merging two distinct vertices, start == target with 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 start and target connect can include an unrelated heavy edge in another part of the graph.
  • Checking root_u == find_root(parent, target) instead of comparing start and target: An edge (u, v) might bridge two middle components — one containing start and one containing target — without u or v being start or target directly. Always test find_root(parent, start) == find_root(parent, target).
  • Writing recursive find_root without union by size: Without balancing tree sizes, an adversarial edge order can build a chain of depth 200,000 and crash with RecursionError.

Alternative approaches

  • Minimax Dijkstra (priority-queue search): Track best_stress[v] (the smallest path stress found so far to reach v) and push (stress, v) onto a min-heap (a binary tree array that always pops the smallest stress next), relaxing neighbors via new_stress = max(stress, weight). Because max(stress, weight) >= stress, stress never decreases along a path, so the first time target is popped from the heap its stress is optimal in O((V + E) log V) time. This also works directly on directed graphs.
  • Binary search on the answer + BFS: Sort the unique edge weights (<= E candidates) and binary search for the smallest weight w where a BFS traversing only edges with weight <= w reaches target. Easy to reason about, running in O((V + E) log E) time across roughly log2(300,000) ≈ 19 BFS 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 the 2^k-th ancestor of v and max_edge[k][v] storing the heaviest edge on that 2^k-step jump) in O(V log V) time and space, which then answers every (start, target) query in O(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 start and target connect (at most V - 1 edges, all with weight <= answer). Build an adjacency list from just those accepted edges and run a single O(V) BFS from start to target, recording came_from[neighbor] = curr so you can walk backward from target to start and 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 (u reaching v does not mean v reaches u). Instead, build a directed adjacency list adj[u] = [(v, weight), ...] and run the minimax Dijkstra algorithm (new_stress = max(curr_stress, weight)) in O((V + E) log V) time, or binary search over the sorted edge weights with a directed BFS check in O((V + E) log E) time.

Follow-up questions

Similar questions

More Walmart Labs interview questions

All 38 Walmart Labs questions →