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 representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.
Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.
Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
Note:
Example 1:
Input: n = 7, cost = [1,5,2,2,3,3,1] Output: 6 Explanation: We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve.
Example 2:
Input: n = 3, cost = [5,3,3] Output: 0 Explanation: The two paths already have equal total costs, so no increments are needed.
Constraints:
3 <= n <= 105n + 1 is a power of 2cost.length == n1 <= cost[i] <= 104Problem summary: You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1. Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times. Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal. Note: A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children. The cost of a path is the sum of costs of nodes in the path.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Greedy · Tree
7 [1,5,2,2,3,3,1]
3 [5,3,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2673: Make Costs of Paths Equal in a Binary Tree
class Solution {
public int minIncrements(int n, int[] cost) {
int ans = 0;
for (int i = n >> 1; i > 0; --i) {
int l = i << 1, r = i << 1 | 1;
ans += Math.abs(cost[l - 1] - cost[r - 1]);
cost[i - 1] += Math.max(cost[l - 1], cost[r - 1]);
}
return ans;
}
}
// Accepted solution for LeetCode #2673: Make Costs of Paths Equal in a Binary Tree
func minIncrements(n int, cost []int) (ans int) {
for i := n >> 1; i > 0; i-- {
l, r := i<<1, i<<1|1
ans += abs(cost[l-1] - cost[r-1])
cost[i-1] += max(cost[l-1], cost[r-1])
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #2673: Make Costs of Paths Equal in a Binary Tree
class Solution:
def minIncrements(self, n: int, cost: List[int]) -> int:
ans = 0
for i in range(n >> 1, 0, -1):
l, r = i << 1, i << 1 | 1
ans += abs(cost[l - 1] - cost[r - 1])
cost[i - 1] += max(cost[l - 1], cost[r - 1])
return ans
// Accepted solution for LeetCode #2673: Make Costs of Paths Equal in a Binary Tree
/**
* [2673] Make Costs of Paths Equal in a Binary Tree
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn min_increments(n: i32, cost: Vec<i32>) -> i32 {
let mut result = 0;
let mut cost = cost;
let mut now = (n - 2) as usize;
loop {
result += (cost[now] - cost[now + 1]).abs();
cost[now / 2] += cost[now].max(cost[now + 1]);
if now <= 2 {
break;
}
now = now - 2;
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2673() {
assert_eq!(Solution::min_increments(7, vec![1, 5, 2, 2, 3, 3, 1]), 6);
}
}
// Accepted solution for LeetCode #2673: Make Costs of Paths Equal in a Binary Tree
function minIncrements(n: number, cost: number[]): number {
let ans = 0;
for (let i = n >> 1; i; --i) {
const [l, r] = [i << 1, (i << 1) | 1];
ans += Math.abs(cost[l - 1] - cost[r - 1]);
cost[i - 1] += Math.max(cost[l - 1], cost[r - 1]);
}
return ans;
}
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: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
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.