LeetCode #3419 — MEDIUM

Minimize the Maximum Edge Weight of Graph

Move from brute-force thinking to an efficient approach using binary search strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given two integers, n and threshold, as well as a directed weighted graph of n nodes numbered from 0 to n - 1. The graph is represented by a 2D integer array edges, where edges[i] = [Ai, Bi, Wi] indicates that there is an edge going from node Ai to node Bi with weight Wi.

You have to remove some edges from this graph (possibly none), so that it satisfies the following conditions:

  • Node 0 must be reachable from all other nodes.
  • The maximum edge weight in the resulting graph is minimized.
  • Each node has at most threshold outgoing edges.

Return the minimum possible value of the maximum edge weight after removing the necessary edges. If it is impossible for all conditions to be satisfied, return -1.

Example 1:

Input: n = 5, edges = [[1,0,1],[2,0,2],[3,0,1],[4,3,1],[2,1,1]], threshold = 2

Output: 1

Explanation:

Remove the edge 2 -> 0. The maximum weight among the remaining edges is 1.

Example 2:

Input: n = 5, edges = [[0,1,1],[0,2,2],[0,3,1],[0,4,1],[1,2,1],[1,4,1]], threshold = 1

Output: -1

Explanation: 

It is impossible to reach node 0 from node 2.

Example 3:

Input: n = 5, edges = [[1,2,1],[1,3,3],[1,4,5],[2,3,2],[3,4,2],[4,0,1]], threshold = 1

Output: 2

Explanation: 

Remove the edges 1 -> 3 and 1 -> 4. The maximum weight among the remaining edges is 2.

Example 4:

Input: n = 5, edges = [[1,2,1],[1,3,3],[1,4,5],[2,3,2],[4,0,1]], threshold = 1

Output: -1

Constraints:

  • 2 <= n <= 105
  • 1 <= threshold <= n - 1
  • 1 <= edges.length <= min(105, n * (n - 1) / 2).
  • edges[i].length == 3
  • 0 <= Ai, Bi < n
  • Ai != Bi
  • 1 <= Wi <= 106
  • There may be multiple edges between a pair of nodes, but they must have unique weights.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given two integers, n and threshold, as well as a directed weighted graph of n nodes numbered from 0 to n - 1. The graph is represented by a 2D integer array edges, where edges[i] = [Ai, Bi, Wi] indicates that there is an edge going from node Ai to node Bi with weight Wi. You have to remove some edges from this graph (possibly none), so that it satisfies the following conditions: Node 0 must be reachable from all other nodes. The maximum edge weight in the resulting graph is minimized. Each node has at most threshold outgoing edges. Return the minimum possible value of the maximum edge weight after removing the necessary edges. If it is impossible for all conditions to be satisfied, return -1.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Binary Search

Example 1

5
[[1,0,1],[2,0,2],[3,0,1],[4,3,1],[2,1,1]]
2

Example 2

5
[[0,1,1],[0,2,2],[0,3,1],[0,4,1],[1,2,1],[1,4,1]]
1

Example 3

5
[[1,2,1],[1,3,3],[1,4,5],[2,3,2],[3,4,2],[4,0,1]]
1
Step 02

Core Insight

What unlocks the optimal approach

  • Can we use binary search?
  • Invert the edges in the graph.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3419: Minimize the Maximum Edge Weight of Graph
class Solution {
  public int minMaxWeight(int n, int[][] pairs, int threshold) {
    final int MAX = 1_000_000;
    List<Pair<Integer, Integer>>[] reversedGraph = new List[n];

    for (int i = 0; i < n; i++)
      reversedGraph[i] = new ArrayList<>();

    for (int[] pair : pairs) {
      final int u = pair[0];
      final int v = pair[1];
      final int w = pair[2];
      reversedGraph[v].add(new Pair<>(u, w));
    }

    int l = 1;
    int r = MAX + 1;

    while (l < r) {
      final int m = (l + r) / 2;
      if (dfs(reversedGraph, 0, m, new boolean[n]) == n)
        r = m;
      else
        l = m + 1;
    }

    return l == (MAX + 1) ? -1 : l;
  }

  // Returns the number of nodes reachable from u with weight <= maxWeight.
  private int dfs(List<Pair<Integer, Integer>>[] reversedGraph, int u, int maxWeight,
                  boolean[] seen) {
    int res = 1;
    seen[u] = true;
    for (Pair<Integer, Integer> pair : reversedGraph[u]) {
      final int v = pair.getKey();
      final int w = pair.getValue();
      if (w > maxWeight || seen[v])
        continue;
      res += dfs(reversedGraph, v, maxWeight, seen);
    }
    return res;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.