Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: edges = [[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]], queries = [[2,3,4],[0,2,5]]
Output: [12,11]
Explanation:
The blue edges represent one of the subtrees that yield the optimal answer.
answer[0]: The total weight of the selected subtree that ensures a path from src1 = 2 and src2 = 3 to dest = 4 is 3 + 5 + 4 = 12.
answer[1]: The total weight of the selected subtree that ensures a path from src1 = 0 and src2 = 2 to dest = 5 is 2 + 3 + 6 = 11.
Example 2:
Input: edges = [[1,0,8],[0,2,7]], queries = [[0,1,2]]
Output: [15]
Explanation:
answer[0]: The total weight of the selected subtree that ensures a path from src1 = 0 and src2 = 1 to dest = 2 is 8 + 7 = 15.Constraints:
3 <= n <= 105edges.length == n - 1edges[i].length == 30 <= ui, vi < n1 <= wi <= 1041 <= queries.length <= 105queries[j].length == 30 <= src1j, src2j, destj < nsrc1j, src2j, and destj are pairwise distinct.edges represents a valid tree.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Bit Manipulation · Tree
[[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]] [[2,3,4],[0,2,5]]
[[1,0,8],[0,2,7]] [[0,1,2]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
class Solution {
// Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
public int[] minimumWeight(int[][] edges, int[][] queries) {
final int n = edges.length + 1;
final int m = (int) Math.ceil(Math.log(n) / Math.log(2));
int[] ans = new int[queries.length];
List<Pair<Integer, Integer>>[] graph = new List[n];
// jump[i][j] := the 2^j-th ancestor of i
int[][] jump = new int[n][m];
// depth[i] := the depth of i
int[] depth = new int[n];
// dist[i] := the distance from root to i
int[] dist = new int[n];
Arrays.setAll(graph, i -> new ArrayList<>());
for (int[] edge : edges) {
final int u = edge[0];
final int v = edge[1];
final int w = edge[2];
graph[u].add(new Pair<>(v, w));
graph[v].add(new Pair<>(u, w));
}
dfs(graph, 0, /*prev=*/-1, jump, depth, dist);
for (int j = 1; j < m; ++j)
for (int i = 0; i < n; ++i)
jump[i][j] = jump[jump[i][j - 1]][j - 1];
for (int i = 0; i < queries.length; ++i) {
final int src1 = queries[i][0];
final int src2 = queries[i][1];
final int dest = queries[i][2];
ans[i] = (distance(src1, src2, jump, depth, dist) + distance(src1, dest, jump, depth, dist) +
distance(src2, dest, jump, depth, dist)) /
2;
}
return ans;
}
private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth,
int[] dist) {
for (Pair<Integer, Integer> pair : graph[u]) {
final int v = pair.getKey();
final int w = pair.getValue();
if (v == prev)
continue;
jump[v][0] = u;
depth[v] = depth[u] + 1;
dist[v] = dist[u] + w;
dfs(graph, v, u, jump, depth, dist);
}
}
// Returns the lca(u, v) by binary jump.
private int getLCA(int u, int v, int[][] jump, int[] depth) {
// v is always deeper than u.
if (depth[u] > depth[v])
return getLCA(v, u, jump, depth);
// Jump v to the same height of u.
for (int j = 0; j < jump[0].length; ++j)
if ((depth[v] - depth[u] >> j & 1) == 1)
v = jump[v][j];
if (u == v)
return u;
// Jump u and v to the node right below the lca.
for (int j = jump[0].length - 1; j >= 0; --j)
if (jump[u][j] != jump[v][j]) {
u = jump[u][j];
v = jump[v][j];
}
return jump[u][0];
}
// Returns the distance between u and v.
private int distance(int u, int v, int[][] jump, int[] depth, int[] dist) {
final int lca = getLCA(u, v, jump, depth);
return dist[u] + dist[v] - 2 * dist[lca];
}
}
// Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
package main
import "math/bits"
// https://space.bilibili.com/206214
func minimumWeight(edges [][]int, queries [][]int) []int {
n := len(edges) + 1
type edge struct{ to, wt int }
g := make([][]edge, n)
for _, e := range edges {
x, y, wt := e[0], e[1], e[2]
g[x] = append(g[x], edge{y, wt})
g[y] = append(g[y], edge{x, wt})
}
const mx = 17
pa := make([][mx]int, n)
dep := make([]int, n)
dis := make([]int, n)
var dfs func(int, int)
dfs = func(x, p int) {
pa[x][0] = p
for _, e := range g[x] {
y := e.to
if y == p {
continue
}
dep[y] = dep[x] + 1
dis[y] = dis[x] + e.wt
dfs(y, x)
}
}
dfs(0, -1)
for i := range mx - 1 {
for x := range pa {
p := pa[x][i]
if p != -1 {
pa[x][i+1] = pa[p][i]
} else {
pa[x][i+1] = -1
}
}
}
uptoDep := func(x, d int) int {
for k := uint(dep[x] - d); k > 0; k &= k - 1 {
x = pa[x][bits.TrailingZeros(k)]
}
return x
}
getLCA := func(x, y int) int {
if dep[x] > dep[y] {
x, y = y, x
}
y = uptoDep(y, dep[x])
if y == x {
return x
}
for i := mx - 1; i >= 0; i-- {
if pv, pw := pa[x][i], pa[y][i]; pv != pw {
x, y = pv, pw
}
}
return pa[x][0]
}
getDis := func(x, y int) int { return dis[x] + dis[y] - dis[getLCA(x, y)]*2 }
// 以上全是 LCA 模板
ans := make([]int, len(queries))
for i, q := range queries {
a, b, c := q[0], q[1], q[2]
ans[i] = (getDis(a, b) + getDis(b, c) + getDis(a, c)) / 2
}
return ans
}
# Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
class Solution:
# Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
def minimumWeight(
self,
edges: list[list[int]],
queries: list[list[int]]
) -> list[int]:
n = len(edges) + 1
m = math.ceil(math.log2(n))
graph = [[] for _ in range(n)]
jump = [[0] * m for _ in range(n)] # jump[i][j] := the 2^j-th ancestor of i
depth = [0] * n # depth[i] := the depth of i
dist = [0] * n # dist[i] := the distance from root to i
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
self._dfs(graph, 0, -1, jump, depth, dist)
for j in range(1, m):
for i in range(n):
jump[i][j] = jump[jump[i][j - 1]][j - 1]
return [(self._distance(src1, src2, jump, depth, dist) +
self._distance(src1, dest, jump, depth, dist) +
self._distance(src2, dest, jump, depth, dist)) // 2
for src1, src2, dest in queries]
def _dfs(
self,
graph: list[list[tuple[int, int]]],
u: int,
prev: int,
jump: list[list[int]],
depth: list[int],
dist: list[int]
) -> None:
for v, w in graph[u]:
if v == prev:
continue
jump[v][0] = u
depth[v] = depth[u] + 1
dist[v] = dist[u] + w
self._dfs(graph, v, u, jump, depth, dist)
def _getLCA(
self,
u: int,
v: int,
jump: list[list[int]],
depth: list[int]
) -> int:
"""Returns the lca(u, v) by binary jump."""
# v is always deeper than u.
if depth[u] > depth[v]:
return self._getLCA(v, u, jump, depth)
# Jump v to the same height of u.
for j in range(len(jump[0])):
if depth[v] - depth[u] >> j & 1:
v = jump[v][j]
if u == v:
return u
# Jump u and v to the node right below the lca.
for j in range(len(jump[0]) - 1, -1, -1):
if jump[u][j] != jump[v][j]:
u = jump[u][j]
v = jump[v][j]
return jump[u][0]
def _distance(
self,
u: int,
v: int,
jump: list[list[int]],
depth: list[int],
dist: list[int]
) -> int:
"""Returns the distance between u and v."""
lca = self._getLCA(u, v, jump, depth)
return dist[u] + dist[v] - 2 * dist[lca]
// Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
// class Solution {
// // Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
// public int[] minimumWeight(int[][] edges, int[][] queries) {
// final int n = edges.length + 1;
// final int m = (int) Math.ceil(Math.log(n) / Math.log(2));
// int[] ans = new int[queries.length];
// List<Pair<Integer, Integer>>[] graph = new List[n];
// // jump[i][j] := the 2^j-th ancestor of i
// int[][] jump = new int[n][m];
// // depth[i] := the depth of i
// int[] depth = new int[n];
// // dist[i] := the distance from root to i
// int[] dist = new int[n];
// Arrays.setAll(graph, i -> new ArrayList<>());
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// final int w = edge[2];
// graph[u].add(new Pair<>(v, w));
// graph[v].add(new Pair<>(u, w));
// }
//
// dfs(graph, 0, /*prev=*/-1, jump, depth, dist);
//
// for (int j = 1; j < m; ++j)
// for (int i = 0; i < n; ++i)
// jump[i][j] = jump[jump[i][j - 1]][j - 1];
//
// for (int i = 0; i < queries.length; ++i) {
// final int src1 = queries[i][0];
// final int src2 = queries[i][1];
// final int dest = queries[i][2];
// ans[i] = (distance(src1, src2, jump, depth, dist) + distance(src1, dest, jump, depth, dist) +
// distance(src2, dest, jump, depth, dist)) /
// 2;
// }
//
// return ans;
// }
//
// private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth,
// int[] dist) {
// for (Pair<Integer, Integer> pair : graph[u]) {
// final int v = pair.getKey();
// final int w = pair.getValue();
// if (v == prev)
// continue;
// jump[v][0] = u;
// depth[v] = depth[u] + 1;
// dist[v] = dist[u] + w;
// dfs(graph, v, u, jump, depth, dist);
// }
// }
//
// // Returns the lca(u, v) by binary jump.
// private int getLCA(int u, int v, int[][] jump, int[] depth) {
// // v is always deeper than u.
// if (depth[u] > depth[v])
// return getLCA(v, u, jump, depth);
// // Jump v to the same height of u.
// for (int j = 0; j < jump[0].length; ++j)
// if ((depth[v] - depth[u] >> j & 1) == 1)
// v = jump[v][j];
// if (u == v)
// return u;
// // Jump u and v to the node right below the lca.
// for (int j = jump[0].length - 1; j >= 0; --j)
// if (jump[u][j] != jump[v][j]) {
// u = jump[u][j];
// v = jump[v][j];
// }
// return jump[u][0];
// }
//
// // Returns the distance between u and v.
// private int distance(int u, int v, int[][] jump, int[] depth, int[] dist) {
// final int lca = getLCA(u, v, jump, depth);
// return dist[u] + dist[v] - 2 * dist[lca];
// }
// }
// Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3553: Minimum Weighted Subgraph With the Required Paths II
// class Solution {
// // Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
// public int[] minimumWeight(int[][] edges, int[][] queries) {
// final int n = edges.length + 1;
// final int m = (int) Math.ceil(Math.log(n) / Math.log(2));
// int[] ans = new int[queries.length];
// List<Pair<Integer, Integer>>[] graph = new List[n];
// // jump[i][j] := the 2^j-th ancestor of i
// int[][] jump = new int[n][m];
// // depth[i] := the depth of i
// int[] depth = new int[n];
// // dist[i] := the distance from root to i
// int[] dist = new int[n];
// Arrays.setAll(graph, i -> new ArrayList<>());
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// final int w = edge[2];
// graph[u].add(new Pair<>(v, w));
// graph[v].add(new Pair<>(u, w));
// }
//
// dfs(graph, 0, /*prev=*/-1, jump, depth, dist);
//
// for (int j = 1; j < m; ++j)
// for (int i = 0; i < n; ++i)
// jump[i][j] = jump[jump[i][j - 1]][j - 1];
//
// for (int i = 0; i < queries.length; ++i) {
// final int src1 = queries[i][0];
// final int src2 = queries[i][1];
// final int dest = queries[i][2];
// ans[i] = (distance(src1, src2, jump, depth, dist) + distance(src1, dest, jump, depth, dist) +
// distance(src2, dest, jump, depth, dist)) /
// 2;
// }
//
// return ans;
// }
//
// private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth,
// int[] dist) {
// for (Pair<Integer, Integer> pair : graph[u]) {
// final int v = pair.getKey();
// final int w = pair.getValue();
// if (v == prev)
// continue;
// jump[v][0] = u;
// depth[v] = depth[u] + 1;
// dist[v] = dist[u] + w;
// dfs(graph, v, u, jump, depth, dist);
// }
// }
//
// // Returns the lca(u, v) by binary jump.
// private int getLCA(int u, int v, int[][] jump, int[] depth) {
// // v is always deeper than u.
// if (depth[u] > depth[v])
// return getLCA(v, u, jump, depth);
// // Jump v to the same height of u.
// for (int j = 0; j < jump[0].length; ++j)
// if ((depth[v] - depth[u] >> j & 1) == 1)
// v = jump[v][j];
// if (u == v)
// return u;
// // Jump u and v to the node right below the lca.
// for (int j = jump[0].length - 1; j >= 0; --j)
// if (jump[u][j] != jump[v][j]) {
// u = jump[u][j];
// v = jump[v][j];
// }
// return jump[u][0];
// }
//
// // Returns the distance between u and v.
// private int distance(int u, int v, int[][] jump, int[] depth, int[] dist) {
// final int lca = getLCA(u, v, jump, depth);
// return dist[u] + dist[v] - 2 * dist[lca];
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.