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.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi] indicates an edge from node ui to vi .
Each node i has an associated cost given by cost[i], representing the cost to traverse that node.
The score of a path is defined as the sum of the costs of all nodes along the path.
Your goal is to make the scores of all root-to-leaf paths equal by increasing the cost of any number of nodes by any non-negative amount.
Return the minimum number of nodes whose cost must be increased to make all root-to-leaf path scores equal.
Example 1:
Input: n = 3, edges = [[0,1],[0,2]], cost = [2,1,3]
Output: 1
Explanation:
There are two root-to-leaf paths:
0 → 1 has a score of 2 + 1 = 3.0 → 2 has a score of 2 + 3 = 5.To make all root-to-leaf path scores equal to 5, increase the cost of node 1 by 2.
Only one node is increased, so the output is 1.
Example 2:
Input: n = 3, edges = [[0,1],[1,2]], cost = [5,1,4]
Output: 0
Explanation:
There is only one root-to-leaf path:
Path 0 → 1 → 2 has a score of 5 + 1 + 4 = 10.
Since only one root-to-leaf path exists, all path costs are trivially equal, and the output is 0.
Example 3:
Input: n = 5, edges = [[0,4],[0,1],[1,2],[1,3]], cost = [3,4,1,1,7]
Output: 1
Explanation:
There are three root-to-leaf paths:
0 → 4 has a score of 3 + 7 = 10.0 → 1 → 2 has a score of 3 + 4 + 1 = 8.0 → 1 → 3 has a score of 3 + 4 + 1 = 8.To make all root-to-leaf path scores equal to 10, increase the cost of node 1 by 2. Thus, the output is 1.
Constraints:
2 <= n <= 105edges.length == n - 1edges[i] == [ui, vi]0 <= ui, vi < ncost.length == n1 <= cost[i] <= 109edges represents a valid tree.Problem summary: You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi] indicates an edge from node ui to vi . Each node i has an associated cost given by cost[i], representing the cost to traverse that node. The score of a path is defined as the sum of the costs of all nodes along the path. Your goal is to make the scores of all root-to-leaf paths equal by increasing the cost of any number of nodes by any non-negative amount. Return the minimum number of nodes whose cost must be increased to make all root-to-leaf path scores equal.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Tree
3 [[0,1],[0,2]] [2,1,3]
3 [[0,1],[1,2]] [5,1,4]
5 [[0,4],[0,1],[1,2],[1,3]] [3,4,1,1,7]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// package main
//
// // https://space.bilibili.com/206214
// func minIncrease(n int, edges [][]int, cost []int) (ans int) {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
// g[0] = append(g[0], -1)
//
// var dfs func(int, int) int
// dfs = func(x, fa int) (maxS int) {
// cnt := 0
// for _, y := range g[x] {
// if y == fa {
// continue
// }
// mx := dfs(y, x)
// if mx > maxS {
// maxS = mx
// cnt = 1
// } else if mx == maxS {
// cnt++
// }
// }
// ans += len(g[x]) - 1 - cnt
// return maxS + cost[x]
// }
// dfs(0, -1)
// return
// }
// Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
package main
// https://space.bilibili.com/206214
func minIncrease(n int, edges [][]int, cost []int) (ans int) {
g := make([][]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
g[0] = append(g[0], -1)
var dfs func(int, int) int
dfs = func(x, fa int) (maxS int) {
cnt := 0
for _, y := range g[x] {
if y == fa {
continue
}
mx := dfs(y, x)
if mx > maxS {
maxS = mx
cnt = 1
} else if mx == maxS {
cnt++
}
}
ans += len(g[x]) - 1 - cnt
return maxS + cost[x]
}
dfs(0, -1)
return
}
# Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
# Time: O(n)
# Space: O(n)
# iterative dfs
class Solution(object):
def minIncrease(self, n, edges, cost):
"""
:type n: int
:type edges: List[List[int]]
:type cost: List[int]
:rtype: int
"""
def iter_dfs():
result = n-1
mx = [0]*len(adj)
stk = [(1, (0, -1))]
while stk:
step, (u, p) = stk.pop()
if step == 1:
stk.append((2, (u, p)))
for v in reversed(adj[u]):
if v != p:
stk.append((1, (v, u)))
elif step == 2:
cnt = 0
for v in adj[u]:
if v == p or mx[v] < mx[u]:
continue
if mx[v] > mx[u]:
mx[u] = mx[v]
cnt = 0
cnt += 1
result -= cnt
mx[u] += cost[u]
return result
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return iter_dfs()
# Time: O(n)
# Space: O(n)
# dfs
class Solution2(object):
def minIncrease(self, n, edges, cost):
"""
:type n: int
:type edges: List[List[int]]
:type cost: List[int]
:rtype: int
"""
def dfs(u, p):
mx = cnt = 0
for v in adj[u]:
if v == p:
continue
c = dfs(v, u)
if c < mx:
continue
if c > mx:
mx = c
cnt = 0
cnt += 1
result[0] -= cnt
return mx+cost[u]
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
result = [n-1]
dfs(0, -1)
return result[0]
// Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// Rust example auto-generated from go 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 (go):
// // Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// package main
//
// // https://space.bilibili.com/206214
// func minIncrease(n int, edges [][]int, cost []int) (ans int) {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
// g[0] = append(g[0], -1)
//
// var dfs func(int, int) int
// dfs = func(x, fa int) (maxS int) {
// cnt := 0
// for _, y := range g[x] {
// if y == fa {
// continue
// }
// mx := dfs(y, x)
// if mx > maxS {
// maxS = mx
// cnt = 1
// } else if mx == maxS {
// cnt++
// }
// }
// ans += len(g[x]) - 1 - cnt
// return maxS + cost[x]
// }
// dfs(0, -1)
// return
// }
// Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3593: Minimum Increments to Equalize Leaf Paths
// package main
//
// // https://space.bilibili.com/206214
// func minIncrease(n int, edges [][]int, cost []int) (ans int) {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
// g[0] = append(g[0], -1)
//
// var dfs func(int, int) int
// dfs = func(x, fa int) (maxS int) {
// cnt := 0
// for _, y := range g[x] {
// if y == fa {
// continue
// }
// mx := dfs(y, x)
// if mx > maxS {
// maxS = mx
// cnt = 1
// } else if mx == maxS {
// cnt++
// }
// }
// ans += len(g[x]) - 1 - cnt
// return maxS + cost[x]
// }
// dfs(0, -1)
// return
// }
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.