Burst Balloons solution explained
Burst Balloons asks for the most coins you can collect by popping every balloon, where popping one pays its value times its current left and right neighbors. The trick is to think about which balloon is popped last between two fixed walls: its neighbors at that moment are the walls themselves, so the two sides become independent subproblems. Pad the list with a 1 at each end and fill best[left][right] over growing widths in O(n³) time.
By Evin JohnPublished 7 min read
The problem, restated
A row of balloons each carries a non-negative number. Popping a balloon earns the product of its number and the numbers of the balloons immediately to its left and right at that moment; a missing neighbor at either end counts as 1. After a pop, the neighbors close the gap. Pop every balloon in some order and return the largest total you can earn.
For the values 2, 4, 3 the best total is 33. Pop 4 first for 2 × 4 × 3 = 24, leaving 2, 3. Pop 2 for 1 × 2 × 3 = 6, then 3 for 1 × 3 × 1 = 3. Popping 2 first instead earns 1 × 2 × 4 = 8, then 4 for 12, then 3 for 3: only 23. The order matters, and nothing local tells you which order is best.
Brute force: every order
from itertools import permutations
def max_coins_brute(nums):
"""Try every popping order: O(n! * n). Only for n up to about 8."""
best = 0
for order in permutations(range(len(nums))):
alive = list(range(len(nums)))
coins = 0
for k in order:
pos = alive.index(k)
left = nums[alive[pos - 1]] if pos > 0 else 1
right = nums[alive[pos + 1]] if pos + 1 < len(alive) else 1
coins += left * nums[k] * right
alive.pop(pos)
best = max(best, coins)
return bestMemoizing on the set of balloons still alive helps a little, but there are 2^n such sets, which is still far too many. The real progress comes from finding subproblems that do not depend on each other.
Why thinking about the first pop fails
If you choose the first balloon to pop, its left and right sides are not independent afterward: the balloons next to the gap become neighbors, so a later pop on the left side earns coins that depend on a balloon from the right side. There is no clean split. Most candidates who get stuck on this problem are stuck here.
Choose the last balloon instead
Put a wall with value 1 at each end, so the list becomes 1, values, 1. Now consider any two positions l and r and the balloons strictly between them. Pick k as the last of those balloons to pop. Until k is popped, it stands between the two sides, so everything left of k (between l and k) is popped with k as a fixed right wall, and everything right of k is popped with k as a fixed left wall. The two sides are now independent. When k finally pops, its neighbors are l and r, so it earns vals[l] × vals[k] × vals[r].
def max_coins(nums):
"""Interval DP on the LAST balloon popped between two fixed walls."""
vals = [1] + nums + [1]
n = len(vals)
best = [[0] * n for _ in range(n)] # best[l][r]: pop everything strictly between l and r
for width in range(2, n):
for left in range(0, n - width):
right = left + width
top = 0
for last in range(left + 1, right):
gain = vals[left] * vals[last] * vals[right]
top = max(top, best[left][last] + gain + best[last][right])
best[left][right] = top
return best[0][n - 1]function maxCoins(nums) {
const vals = [1, ...nums, 1];
const n = vals.length;
const best = Array.from({ length: n }, () => new Array(n).fill(0));
for (let width = 2; width < n; width++) {
for (let left = 0; left + width < n; left++) {
const right = left + width;
let top = 0;
for (let last = left + 1; last < right; last++) {
const gain = vals[left] * vals[last] * vals[right];
top = Math.max(top, best[left][last] + gain + best[last][right]);
}
best[left][right] = top;
}
}
return best[0][n - 1];
}A worked fill for 2, 4, 3
| Interval (l, r) | Balloons inside | Best last choice | best[l][r] |
|---|---|---|---|
| (0, 2) | 2 | 2: 1 × 2 × 4 | 8 |
| (1, 3) | 4 | 4: 2 × 4 × 3 | 24 |
| (2, 4) | 3 | 3: 4 × 3 × 1 | 12 |
| (0, 3) | 2, 4 | 2 last: best[1][3] + 1 × 2 × 3 | 30 |
| (1, 4) | 4, 3 | 3 last: best[1][3] + 2 × 3 × 1 | 30 |
| (0, 4) | 2, 4, 3 | 3 last: best[0][3] + 1 × 3 × 1 | 33 |
For (0, 3), popping 2 last means 4 goes first between walls 2 and 3 (best[1][3] = 24), then 2 between walls 1 and 3 earns 6, total 30; popping 4 last gives best[0][2] = 8 plus 1 × 4 × 3 = 12, total 20. So 30. The full answer picks 3 as the very last balloon: 30 from clearing 2 and 4 first, plus 3 at the end, for 33, matching the order found by hand above.
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Every popping order | O(n! × n) | O(n) |
| Memo on the set of alive balloons | O(2^n × n²) roughly | O(2^n) |
| Interval DP on the last pop | O(n³) | O(n²) |
There are about n²/2 intervals and up to n choices of k for each, hence O(n³). That is fine for a few hundred balloons and is the expected answer; no faster general method is usually asked for.
Edge cases
- No balloons: 0.
- One balloon: its own value, since both neighbors are walls of 1.
- Zeros: a zero balloon earns nothing and wipes out any pop that has it as a neighbor, so it is usually best popped early; the DP handles it without special code.
- Large values: products of three values add up quickly; use 64-bit integers in fixed-width languages if values can be large.
Where answers go wrong
- Defining the subproblem by the first balloon popped, which does not split cleanly.
- Forgetting the padding, then special-casing the ends and getting one of them wrong.
- Using inclusive interval bounds and counting the walls as balloons.
- Filling the table in the wrong order, so best[l][k] is read before it is computed. Grow by width.
- Greedy heuristics such as always popping the smallest value first; small inputs break them quickly.
How to explain it out loud
Fictional example
- Candidate
- If I pick which balloon pops first, the two sides start touching, so I cannot solve them separately. Let me flip it: which balloon pops last between two walls?
- Candidate
- If k is last between l and r, then until the end k separates the left part from the right part. Each side is its own problem with fixed walls, and k pays vals[l] times vals[k] times vals[r] at the end.
- Interviewer
- How do you handle the ends of the row?
- Candidate
- Pad with a 1 on each side and never pop those. Then the answer is best between the two padding walls. I fill intervals from narrow to wide, so the pieces exist when I need them. Cubic time, quadratic memory.
Same idea, other problems
- Cheapest order to multiply a chain of matrices. Choose the last multiplication split; same O(n³) table.
- Cheapest way to cut a stick at given marks. Choose the first cut in an interval; the cost is the interval's length.
- Merge piles of stones in a row at minimum cost. Choose the last merge point.
Related walkthroughs
Unique Paths II is the gentlest DP in this set, a good warm-up before interval DP. Wildcard Matching is a prefix DP, the other common table shape. The coding problems hub lists every walkthrough.
Preparing hard DP problems with Natively
Burst Balloons is usually passed or failed on one sentence: "choose the last one, not the first". When you rehearse, Natively can transcribe the attempt on your Mac or Windows computer so you can see how long it took you to reach that sentence and whether you justified it. In study time, a screenshot of a similar interval problem plus the question "what should the subproblem be?" gets you a hint without the whole answer. The coding interview assistant page describes the coding features.
Questions people ask
How do you solve Burst Balloons?
Pad the values with a 1 on each side. For every interval between two walls, try each balloon as the last one popped: its coins are wall × balloon × wall, plus the best for the left and right parts. Fill intervals from narrow to wide.
Why choose the last balloon instead of the first?
After the first pop, the two sides become neighbors and depend on each other. The last balloon stands between them until the end, so the sides are independent.
What is the time complexity of Burst Balloons?
O(n³) time and O(n²) memory: about n²/2 intervals, each trying up to n last balloons.
What kind of dynamic programming is Burst Balloons?
Interval DP, like matrix chain multiplication: the state is a range, and each range is split at a chosen point.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
