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.
There is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi.
Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.
The cost of a path between any two nodes u and v is the total weight of all edges in the path connecting them.
You are given a 2D integer array queries. For each queries[i] = [ui, vi], determine the number of ways to assign weights to edges in the path such that the cost of the path between ui and vi is odd.
Return an array answer, where answer[i] is the number of valid assignments for queries[i].
Since the answer may be large, apply modulo 109 + 7 to each answer[i].
Note: For each query, disregard all edges not in the path between node ui and vi.
Example 1:
Input: edges = [[1,2]], queries = [[1,1],[1,2]]
Output: [0,1]
Explanation:
[1,1]: The path from Node 1 to itself consists of no edges, so the cost is 0. Thus, the number of valid assignments is 0.[1,2]: The path from Node 1 to Node 2 consists of one edge (1 → 2). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.Example 2:
Input: edges = [[1,2],[1,3],[3,4],[3,5]], queries = [[1,4],[3,4],[2,5]]
Output: [2,1,4]
Explanation:
[1,4]: The path from Node 1 to Node 4 consists of two edges (1 → 3 and 3 → 4). Assigning weights (1,2) or (2,1) results in an odd cost. Thus, the number of valid assignments is 2.[3,4]: The path from Node 3 to Node 4 consists of one edge (3 → 4). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.[2,5]: The path from Node 2 to Node 5 consists of three edges (2 → 1, 1 → 3, and 3 → 5). Assigning (1,2,2), (2,1,2), (2,2,1), or (1,1,1) makes the cost odd. Thus, the number of valid assignments is 4.Constraints:
2 <= n <= 105edges.length == n - 1edges[i] == [ui, vi]1 <= queries.length <= 105queries[i] == [ui, vi]1 <= ui, vi <= nedges represents a valid tree.Problem summary: There is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi. Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2. The cost of a path between any two nodes u and v is the total weight of all edges in the path connecting them. You are given a 2D integer array queries. For each queries[i] = [ui, vi], determine the number of ways to assign weights to edges in the path such that the cost of the path between ui and vi is odd. Return an array answer, where answer[i] is the number of valid assignments for queries[i]. Since the answer may be large, apply modulo 109 + 7 to each answer[i]. Note: For each query, disregard all edges not in the path between node ui and vi.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming · Bit Manipulation · Tree
[[1,2]] [[1,1],[1,2]]
[[1,2],[1,3],[3,4],[3,5]] [[1,4],[3,4],[2,5]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights II
class Solution {
public int[] assignEdgeWeights(int[][] edges, int[][] queries) {
final int n = edges.length + 1;
int[] ans = new int[queries.length];
final int[] depth = new int[n + 1];
final int[][] parent = new int[LOG][n + 1];
List<Integer>[] graph = new List[n + 1];
Arrays.setAll(graph, i -> new ArrayList<>());
for (int[] edge : edges) {
final int u = edge[0];
final int v = edge[1];
graph[u].add(v);
graph[v].add(u);
}
dfs(1, -1, graph, parent, depth);
for (int k = 1; k < LOG; ++k)
for (int v = 1; v <= n; ++v)
if (parent[k - 1][v] != -1)
parent[k][v] = parent[k - 1][parent[k - 1][v]];
for (int i = 0; i < queries.length; ++i) {
final int u = queries[i][0];
final int v = queries[i][1];
if (u == v) {
ans[i] = 0;
} else {
final int a = lca(u, v, parent, depth);
final int d = depth[u] + depth[v] - 2 * depth[a];
ans[i] = modPow(2, d - 1);
}
}
return ans;
}
private static final int MOD = 1_000_000_007;
private static final int LOG = 17; // since 2^17 > 1e5
private void dfs(int u, int p, java.util.List<Integer>[] graph, int[][] parent, int[] depth) {
parent[0][u] = p;
for (int v : graph[u]) {
if (v != p) {
depth[v] = depth[u] + 1;
dfs(v, u, graph, parent, depth);
}
}
}
private int lca(int u, int v, int[][] parent, int[] depth) {
if (depth[u] < depth[v]) {
final int temp = u;
u = v;
v = temp;
}
for (int k = LOG - 1; k >= 0; --k)
if (parent[k][u] != -1 && depth[parent[k][u]] >= depth[v])
u = parent[k][u];
if (u == v)
return u;
for (int k = LOG - 1; k >= 0; --k)
if (parent[k][u] != -1 && parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
return parent[0][u];
}
private int modPow(long x, long n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return (int) (x * modPow(x % MOD, (n - 1)) % MOD);
return modPow(x * x % MOD, (n / 2)) % MOD;
}
}
// Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights II
package main
import "math/bits"
// https://space.bilibili.com/206214
const mod = 1_000_000_007
var pow2 = [1e5]int{1}
func init() {
// 预处理 2 的幂
for i := 1; i < len(pow2); i++ {
pow2[i] = pow2[i-1] * 2 % mod
}
}
func assignEdgeWeights(edges [][]int, queries [][]int) []int {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
x, y := e[0]-1, e[1]-1
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
const mx = 17
pa := make([][mx]int, n)
dep := make([]int, n)
var dfs func(int, int)
dfs = func(x, p int) {
pa[x][0] = p
for _, y := range g[x] {
if y != p {
dep[y] = dep[x] + 1
dfs(y, x)
}
}
}
dfs(0, -1)
for i := range mx - 1 {
for x := range pa {
if p := pa[x][i]; 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 dep[x] + dep[y] - dep[getLCA(x, y)]*2 }
ans := make([]int, len(queries))
for i, q := range queries {
if q[0] != q[1] {
ans[i] = pow2[getDis(q[0]-1, q[1]-1)-1]
}
}
return ans
}
# Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights II
class Solution:
def assignEdgeWeights(
self,
edges: list[list[int]],
queries: list[list[int]]
) -> list[int]:
MOD = 1_000_000_007
LOG = 17 # since 2^17 > 1e5
n = len(edges) + 1
ans = []
depth = [0] * (n + 1)
graph = [[] for _ in range(n + 1)]
parent = [[-1] * (n + 1) for _ in range(LOG)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def dfs(u: int, p: int) -> None:
parent[0][u] = p
for v in graph[u]:
if v != p:
depth[v] = depth[u] + 1
dfs(v, u)
dfs(1, -1)
for k in range(1, LOG):
for v in range(1, n + 1):
if parent[k - 1][v] != -1:
parent[k][v] = parent[k - 1][parent[k - 1][v]]
def lca(u: int, v: int) -> int:
if depth[u] < depth[v]:
u, v = v, u
for k in reversed(range(LOG)):
if parent[k][u] != -1 and depth[parent[k][u]] >= depth[v]:
u = parent[k][u]
if u == v:
return u
for k in reversed(range(LOG)):
if parent[k][u] != -1 and parent[k][u] != parent[k][v]:
u = parent[k][u]
v = parent[k][v]
return parent[0][u]
for u, v in queries:
if u == v:
ans.append(0)
else:
a = lca(u, v)
d = depth[u] + depth[v] - 2 * depth[a]
ans.append(pow(2, d - 1, MOD))
return ans
// Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights 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 #3559: Number of Ways to Assign Edge Weights II
// class Solution {
// public int[] assignEdgeWeights(int[][] edges, int[][] queries) {
// final int n = edges.length + 1;
// int[] ans = new int[queries.length];
// final int[] depth = new int[n + 1];
// final int[][] parent = new int[LOG][n + 1];
// List<Integer>[] graph = new List[n + 1];
// Arrays.setAll(graph, i -> new ArrayList<>());
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// graph[u].add(v);
// graph[v].add(u);
// }
//
// dfs(1, -1, graph, parent, depth);
//
// for (int k = 1; k < LOG; ++k)
// for (int v = 1; v <= n; ++v)
// if (parent[k - 1][v] != -1)
// parent[k][v] = parent[k - 1][parent[k - 1][v]];
//
// for (int i = 0; i < queries.length; ++i) {
// final int u = queries[i][0];
// final int v = queries[i][1];
// if (u == v) {
// ans[i] = 0;
// } else {
// final int a = lca(u, v, parent, depth);
// final int d = depth[u] + depth[v] - 2 * depth[a];
// ans[i] = modPow(2, d - 1);
// }
// }
//
// return ans;
// }
//
// private static final int MOD = 1_000_000_007;
// private static final int LOG = 17; // since 2^17 > 1e5
//
// private void dfs(int u, int p, java.util.List<Integer>[] graph, int[][] parent, int[] depth) {
// parent[0][u] = p;
// for (int v : graph[u]) {
// if (v != p) {
// depth[v] = depth[u] + 1;
// dfs(v, u, graph, parent, depth);
// }
// }
// }
//
// private int lca(int u, int v, int[][] parent, int[] depth) {
// if (depth[u] < depth[v]) {
// final int temp = u;
// u = v;
// v = temp;
// }
//
// for (int k = LOG - 1; k >= 0; --k)
// if (parent[k][u] != -1 && depth[parent[k][u]] >= depth[v])
// u = parent[k][u];
//
// if (u == v)
// return u;
//
// for (int k = LOG - 1; k >= 0; --k)
// if (parent[k][u] != -1 && parent[k][u] != parent[k][v]) {
// u = parent[k][u];
// v = parent[k][v];
// }
//
// return parent[0][u];
// }
//
// private int modPow(long x, long n) {
// if (n == 0)
// return 1;
// if (n % 2 == 1)
// return (int) (x * modPow(x % MOD, (n - 1)) % MOD);
// return modPow(x * x % MOD, (n / 2)) % MOD;
// }
// }
// Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3559: Number of Ways to Assign Edge Weights II
// class Solution {
// public int[] assignEdgeWeights(int[][] edges, int[][] queries) {
// final int n = edges.length + 1;
// int[] ans = new int[queries.length];
// final int[] depth = new int[n + 1];
// final int[][] parent = new int[LOG][n + 1];
// List<Integer>[] graph = new List[n + 1];
// Arrays.setAll(graph, i -> new ArrayList<>());
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// graph[u].add(v);
// graph[v].add(u);
// }
//
// dfs(1, -1, graph, parent, depth);
//
// for (int k = 1; k < LOG; ++k)
// for (int v = 1; v <= n; ++v)
// if (parent[k - 1][v] != -1)
// parent[k][v] = parent[k - 1][parent[k - 1][v]];
//
// for (int i = 0; i < queries.length; ++i) {
// final int u = queries[i][0];
// final int v = queries[i][1];
// if (u == v) {
// ans[i] = 0;
// } else {
// final int a = lca(u, v, parent, depth);
// final int d = depth[u] + depth[v] - 2 * depth[a];
// ans[i] = modPow(2, d - 1);
// }
// }
//
// return ans;
// }
//
// private static final int MOD = 1_000_000_007;
// private static final int LOG = 17; // since 2^17 > 1e5
//
// private void dfs(int u, int p, java.util.List<Integer>[] graph, int[][] parent, int[] depth) {
// parent[0][u] = p;
// for (int v : graph[u]) {
// if (v != p) {
// depth[v] = depth[u] + 1;
// dfs(v, u, graph, parent, depth);
// }
// }
// }
//
// private int lca(int u, int v, int[][] parent, int[] depth) {
// if (depth[u] < depth[v]) {
// final int temp = u;
// u = v;
// v = temp;
// }
//
// for (int k = LOG - 1; k >= 0; --k)
// if (parent[k][u] != -1 && depth[parent[k][u]] >= depth[v])
// u = parent[k][u];
//
// if (u == v)
// return u;
//
// for (int k = LOG - 1; k >= 0; --k)
// if (parent[k][u] != -1 && parent[k][u] != parent[k][v]) {
// u = parent[k][u];
// v = parent[k][v];
// }
//
// return parent[0][u];
// }
//
// private int modPow(long x, long n) {
// if (n == 0)
// return 1;
// if (n % 2 == 1)
// return (int) (x * modPow(x % MOD, (n - 1)) % MOD);
// return modPow(x * x % MOD, (n / 2)) % MOD;
// }
// }
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: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
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.