Minimum Weighted Subgraph With the Required Paths - Problem
Minimum Weighted Subgraph With the Required Paths
You're given a weighted directed graph with
The graph is represented by an array
Goal: Find the minimum total weight of edges needed to create paths from both
Key Insight: The optimal subgraph will likely have paths that converge at some intermediate node before reaching the destination, allowing edge sharing to minimize total weight.
You're given a weighted directed graph with
n nodes (numbered 0 to n-1) and need to find the minimum weight subgraph that allows both src1 and src2 to reach a common destination dest.The graph is represented by an array
edges where edges[i] = [from, to, weight] represents a directed edge from node from to node to with the given weight.Goal: Find the minimum total weight of edges needed to create paths from both
src1 → dest and src2 → dest. The paths can share common edges (which helps minimize the total weight).Key Insight: The optimal subgraph will likely have paths that converge at some intermediate node before reaching the destination, allowing edge sharing to minimize total weight.
Input & Output
example_1.py — Basic convergence case
$
Input:
n = 6, edges = [[0,2,2],[0,5,6],[1,2,3],[1,4,5],[2,3,1],[2,4,2],[3,5,1],[4,5,1]], src1 = 0, src2 = 1, dest = 5
›
Output:
7
💡 Note:
Optimal solution: paths converge at node 2. Path 0→2 (cost 2) + path 1→2 (cost 3) + shared path 2→3→5 (cost 2). Total unique edges: 0→2 (2) + 1→2 (3) + 2→3 (1) + 3→5 (1) = 7.
example_2.py — No shared path optimal
$
Input:
n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 2, dest = 1
›
Output:
2
💡 Note:
Both sources go directly to destination: 0→1 (cost 1) + 2→1 (cost 1) = total cost 2. No benefit from trying to converge paths since they already end at the same destination.
example_3.py — Impossible case
$
Input:
n = 4, edges = [[0,1,1],[1,2,1]], src1 = 0, src2 = 3, dest = 2
›
Output:
-1
💡 Note:
src2 (node 3) has no outgoing edges, so it's impossible to reach dest (node 2) from src2. Since both sources must be able to reach the destination, return -1.
Constraints
- 3 ≤ n ≤ 105
- 0 ≤ edges.length ≤ 105
- edges[i].length == 3
- 0 ≤ fromi, toi, src1, src2, dest ≤ n - 1
- fromi ≠ toi
- src1, src2, and dest are pairwise distinct
- 1 ≤ weighti ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code