#3419

Minimize the Maximum Edge Weight of Graph

Medium
Binary SearchDepth-First SearchBreadth-First SearchGraph TheoryShortest PathBinary SearchGraph TraversalGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(n)
💡

Intuition

Time O(n log m)Space O(n)

The optimal solution uses binary search on the maximum edge weight combined with a graph traversal to check if we can reach node 0 under the weight constraint. This significantly reduces the number of combinations we need to check.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the edges based on their weights.
  2. 2Step 2: Use binary search on the edge weights to find the minimum maximum weight that allows all nodes to reach node 0.
  3. 3Step 3: For each mid value in the binary search, create a subgraph with edges that have weights less than or equal to mid, and check if node 0 is reachable from all other nodes using BFS or DFS.
solution.py34 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def can_reach_zero(n, graph):
5    visited = [False] * n
6    queue = deque([0])
7    while queue:
8        node = queue.popleft()
9        visited[node] = True
10        for neighbor in graph[node]:
11            if not visited[neighbor]:
12                queue.append(neighbor)
13    return all(visited)
14
15
16def min_max_edge_weight(n, edges, threshold):
17    edges.sort(key=lambda x: x[2])
18    left, right = 0, edges[-1][2]
19    while left < right:
20        mid = (left + right) // 2
21        graph = defaultdict(list)
22        outgoing = [0] * n
23        for u, v, w in edges:
24            if w <= mid:
25                graph[u].append(v)
26                outgoing[u] += 1
27            if outgoing[u] > threshold:
28                break
29        else:
30            if can_reach_zero(n, graph):
31                right = mid
32            else:
33                left = mid + 1
34    return left if left <= edges[-1][2] else -1

Complexity note: The time complexity is O(n log m) where n is the number of nodes and m is the number of edges. The binary search runs log m times, and each reachability check runs in O(n) time.

  • 1Binary search allows us to efficiently narrow down the maximum edge weight.
  • 2Graph traversal techniques (DFS/BFS) are essential for checking reachability.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.