KatInterview

Find the Bottleneck Weight Between Two Nodes

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphunion-findgreedy

Last updated

Compute the smallest possible maximum edge weight along any path connecting two vertices in a weighted undirected graph.

You have an undirected graph with weighted edges. Given two vertices, source and destination, you need to find a path between them that minimizes the heaviest edge along the way. Return this minimum achievable maximum edge weight, or -1 if no path exists.

Task

Write a function that takes:

  • n: the number of vertices (labeled 0 through n - 1)
  • edges: a list of tuples (u, v, weight) representing undirected edges
  • source: the starting vertex
  • destination: the ending vertex

Return the smallest value w such that there exists a path from source to destination where every edge has weight at most w. If the two vertices are not connected, return -1. If source equals destination, return 0 (the empty path uses no edges).

Details

  • Each edge (u, v, weight) can be traversed in both directions.
  • Multiple edges between the same pair of vertices are allowed.
  • Edge weights are positive integers.

Constraints

  • 1 ≤ n ≤ 200,000
  • 0 ≤ len(edges) ≤ 300,000
  • 1 ≤ weight ≤ 10^9
  • 0 ≤ source, destination < n

Examples

Example 1

Input: min_bottleneck_weight(5, [[0, 1, 8], [0, 2, 3], [2, 1, 4], [1, 3, 6], [2, 3, 10]], 0, 3)

Output: 6

Hints

Hint 1

Think about what happens when you only allow edges up to a certain weight threshold—does increasing the threshold help or hurt connectivity?

Hint 2

Sort the edges by weight and add them incrementally. Track when the two endpoints first become connected.

Hint 3

A union-find data structure can efficiently maintain connected components as you add edges one by one.