KatInterview

Balance Path Totals in a Rooted Tree with Minimum Bumps

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstreegreedybfs

Last 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_000
  • 0 <= weights[i] <= 10**9
  • parent_of[0] == -1
  • For i > 0, 0 <= parent_of[i] < len(weights).
  • parent_of describes 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.