Minimum Weighted Subgraph With the Required Paths II - Problem

You are given an undirected weighted tree with n nodes, numbered from 0 to n - 1. It is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi.

Additionally, you are given a 2D integer array queries, where queries[j] = [src1j, src2j, destj].

Return an array answer of length equal to queries.length, where answer[j] is the minimum total weight of a subtree such that it is possible to reach destj from both src1j and src2j using edges in this subtree.

A subtree here is any connected subset of nodes and edges of the original tree forming a valid tree.

Input & Output

Example 1 — Basic Tree Query
$ Input: edges = [[0,1,1],[1,2,1],[2,3,2]], queries = [[0,3,2]]
Output: [4]
💡 Note: To connect nodes 0 and 3 to destination 2, we need the path 0→1→2 (weight 2) and path 3→2 (weight 2). Total minimum weight is 4.
Example 2 — Multiple Queries
$ Input: edges = [[0,1,1],[1,2,2],[1,3,3]], queries = [[0,2,3],[2,3,1]]
Output: [6,5]
💡 Note: Query 1: Connect 0,2 to 3 via node 1, weight = 1+2+3 = 6. Query 2: Connect 2,3 to 1, weight = 2+3 = 5.
Example 3 — Same Source and Destination
$ Input: edges = [[0,1,1],[1,2,1]], queries = [[0,0,1]]
Output: [1]
💡 Note: Both sources are node 0, destination is 1. Only need path 0→1 with weight 1.

Constraints

  • 1 ≤ n ≤ 104
  • edges.length == n - 1
  • 0 ≤ ui, vi ≤ n - 1
  • 1 ≤ wi ≤ 106
  • 1 ≤ queries.length ≤ 104
  • 0 ≤ src1j, src2j, destj ≤ n - 1

Visualization

Tap to expand
INPUT TREE0123112Query: [0, 3, 2]src1=0, src2=3, dest=2ALGORITHM STEPS1Build Tree with DFSEstablish parent relationships2Find LCA(0, 3, 2)LCA of all three nodes = 03Calculate Path Weights0→0: 0, 3→0: 3, 2→0: 14Sum Total WeightTotal = 0 + 3 + 1 = 4FINAL RESULT[4]Minimum weightSubtree connects bothsources to destinationKey Insight:The minimal subtree is the union of paths from the LCA to all three nodes.Use DFS preprocessing and LCA finding for efficient O(n + q×n) solution.TutorialsPoint - Minimum Weighted Subgraph With Required Paths II | DFS + LCA Approach
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen