LeetCode #3593 — MEDIUM

Minimum Increments to Equalize Leaf Paths

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

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:

  • Path 0 → 1 has a score of 2 + 1 = 3.
  • Path 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:

  • Path 0 → 4 has a score of 3 + 7 = 10.
  • Path 0 → 1 → 2 has a score of 3 + 4 + 1 = 8.
  • Path 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 <= 105
  • edges.length == n - 1
  • edges[i] == [ui, vi]
  • 0 <= ui, vi < n
  • cost.length == n
  • 1 <= cost[i] <= 109
  • The input is generated such that edges represents a valid tree.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Dynamic Programming · Tree

Example 1

3
[[0,1],[0,2]]
[2,1,3]

Example 2

3
[[0,1],[1,2]]
[5,1,4]

Example 3

5
[[0,4],[0,1],[1,2],[1,3]]
[3,4,1,1,7]
Step 02

Core Insight

What unlocks the optimal approach

  • Every root-to-leaf path's score must be raised to <code>maxLeafCost</code>, the maximum sum among all root-to-leaf paths.
  • For each <code>node</code>, compute <code>minIncrease[node]</code>, the minimum additional cost required so that every root-to-leaf path passing through that <code>node</code> reaches <code>maxLeafCost</code>.
  • The final answer, <code>ans</code>, is the count of <code>nodes</code> for which <code>minIncrease[node]</code> differs from <code>minIncrease[parent]</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

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
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

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.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

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.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

State misses one required dimension

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.

Forgetting null/base-case handling

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.