Balance Path Totals in a Rooted Tree with Minimum Bumps
Trees & GraphsAuto-graded · 21 test casesLast updated
Compute the fewest +1 increments that make every root-to-leaf path total equal in a large rooted tree given as a parent array, which needs a bottom-up greedy and an iterative traversal.
Balance Path Totals in a Rooted Tree with Minimum Bumps
A rooted tree has n nodes numbered 0 to n - 1. Node i carries a nonnegative integer weight weights[i]. A single bump adds 1 to the weight of any one node of your choice, and you may bump the same node many times.
The path total of a leaf is the sum of the weights of all nodes on the path from the root down to that leaf, with both endpoints included. A leaf is a node with no children. If the tree is a single node, that node is both the root and the only leaf.
Return the minimum number of bumps needed so that every leaf has the same path total.
Input format
The tree is given as a parent array. Node 0 is the root and parent_of[0] == -1. For every other node i, parent_of[i] is the index of its parent. A node may have any number of children.
Function
Implement min_bumps_to_balance(weights, parent_of). It returns a single integer, the minimum number of bumps.
Constraints
1 <= len(weights) == len(parent_of) <= 200_0000 <= weights[i] <= 10**9parent_of[0] == -1- For
i > 0,0 <= parent_of[i] < len(weights). parent_ofdescribes one valid rooted tree. A parent's index is not guaranteed to be smaller than its child's.- The tree can be deeper than Python's default recursion limit, so avoid plain recursion.
Examples
Example 1
Input: min_bumps_to_balance([2, 3, 4], [-1, 0, 0])
Output: 1
Example 2
Input: min_bumps_to_balance([1], [-1])
Output: 0
Example 3
Input: min_bumps_to_balance([0, 0, 0, 0, 0], [-1, 0, 0, 1, 2])
Output: 0
Hints
Hint 1
Each subtree can be summarized by one number: the smallest common root-to-leaf total it can reach, counting its own top node. Compute these from the leaves upward.
Hint 2
At a node with several children, every child subtree must end at the same total, and totals can only increase. So the cheapest common level is the maximum of the children's summaries. Raise each smaller child up to that level.
Hint 3
Put all of a child's raise on the child node itself, since one bump there lifts every path below it. Do not sum per-leaf deficits, because leaves sharing an ancestor would be overcounted. Build a BFS order from the root and walk it in reverse to avoid recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Work from the leaves up. For each node u, define level[u] as the smallest common root-to-leaf total that its subtree can reach, measured from u downward and including weights[u].
- Leaf:
level[u] = weights[u], and no bumps are needed. - Internal node: every child subtree is already balanced internally at its own
level[c]. All children must finish at the same total, and bumps can only raise totals. The cheapest shared target istop = max(level[c]). Each childcis raised bytop - level[c], and all of that raise goes on nodecitself. Thenlevel[u] = weights[u] + top.
The answer is the sum of all these raises.
To avoid recursion on deep trees, build the child lists, produce a BFS order from the root, and process it in reverse. In that order every child appears before its parent. This does not depend on parent indices being smaller than child indices.
Why it is correct
Let f_u(L) be the minimum cost to make every path in u's subtree total exactly L, counted from u. Let cost_u be the greedy cost. By induction, f_u(L) = cost_u + (L - level[u]) for all L >= level[u], and smaller L is impossible.
- Leaf: we must add
L - weights[u]to it, so the formula holds. - Internal node with
k >= 1children: suppose we addxbumps tou. Each child must then reachL' = L - weights[u] - x, which requiresL' >= top. By induction the total cost is a constant plusx * (1 - k). Since1 - k <= 0, a largerxnever costs more, so the best choice is the largest feasiblex, which givesL' = top. Substituting gives exactlycost_u + (L - level[u]).
In words, a bump higher in the tree affects at least as many leaves as a bump below it, so pushing raises upward is never worse. At the root the cost is smallest at L = level[root], so the answer is cost_root.
Summing max_path_total - leaf_path_total over all leaves is wrong because sibling leaves can share a single bump on a common ancestor.
Complexity
- Time:
O(n). Building child lists, the BFS order, and the reverse pass each touch every node and edge a constant number of times. - Space:
O(n)for the child lists, the order, andlevel.
Reference solution
from typing import List
def min_bumps_to_balance(weights: List[int], parent_of: List[int]) -> int:
n = len(weights)
kids = [[] for _ in range(n)]
for node in range(1, n):
kids[parent_of[node]].append(node)
# BFS order from the root; reversed, every child precedes its parent.
order = [0]
for node in order:
order.extend(kids[node])
level = [0] * n # level[u]: balanced root-to-leaf total inside u's subtree, including weights[u]
bumps = 0
for node in reversed(order):
children = kids[node]
if not children:
level[node] = weights[node]
continue
top = max(level[c] for c in children)
bumps += sum(top - level[c] for c in children)
level[node] = weights[node] + top
return bumps