Minimize Increments to Equalize Path Costs
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree data structures, root-to-leaf path aggregation, and cost-balancing strategies within the Coding & Algorithms domain.
Constraints
- 1 <= n <= 10^5
- n = 2^h - 1 for some integer h >= 1
- len(cost) == n
- 1 <= cost[i] <= 10^4
Examples
Input: (7, [1, 5, 2, 2, 3, 3, 1])
Expected Output: 6
Explanation: At node 2, its children differ by 1; at node 3, its children differ by 2; after that, the two subtrees under the root differ by 3. Total operations = 1 + 2 + 3 = 6.
Input: (1, [7])
Expected Output: 0
Explanation: There is only one root-to-leaf path, so all path costs are already equal.
Input: (7, [1, 2, 3, 4, 5, 6, 7])
Expected Output: 5
Explanation: Balance the children of node 2 with 1 increment, balance the children of node 3 with 1 increment, then balance the two subtrees at the root with 3 more increments.
Input: (15, [1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2])
Expected Output: 4
Explanation: Each leaf pair under nodes 4, 5, 6, and 7 differs by 1, so 4 operations make all four lower subtrees balanced. Higher levels are then already balanced.
Input: (7, [4, 2, 2, 1, 1, 1, 1])
Expected Output: 0
Explanation: All root-to-leaf path sums are already 7, so no increments are needed.
Hints
- Work from the bottom of the tree upward. For each parent, compare the best path sum coming from its left child and right child.
- If one subtree path sum is smaller, you must add exactly the difference to that subtree. After balancing, the parent contributes its own cost plus the larger of the two child path sums.