Cheapest Aggregation Tree Over Ordered Shard Sizes
Last updated: November 29, 2026
Quick Overview
Leaves of a full binary tree are shard sizes in a fixed left-to-right order; each internal node costs the product of the largest leaf in its left subtree and the largest leaf in its right subtree. Return the minimum total cost.
Meta
November 29, 20260
0
0 solved
Leaves of a full binary tree are shard sizes in a fixed left-to-right order; each internal node costs the product of the largest leaf in its left subtree and the largest leaf in its right subtree. Return the minimum total cost.
Meta interviewers use this as a problem that has an obvious interval DP and a much faster greedy with a monotonic stack. Framed as building a merge tree for ordered log shards, it checks whether you can spot that the smallest leaf should be merged first with its smaller neighbor.
What the Interviewer Expects
- Formulate the O(n^3) interval DP
- Observe the cost of removing a leaf is its value times the smaller neighbor
- Greedily remove local minima using a decreasing stack
- Flush the remaining stack at the end
- Argue why the greedy is optimal
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Reconstruct the tree shape.
- What if the cost is the sum instead of the product?
- Prove the greedy with an exchange argument.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list a of positive integers, length 2 to 40 in the classic version, longer here. Output: the minimum sum of internal node values over all full binary trees whose in-order leaves are a. Each...
High-Level Design
Building the tree is equivalent to repeatedly merging two adjacent items, paying the product of their values, and keeping the larger one. A leaf x is merged away when it meets a neighbor, and the chea...