On this page · Let Endpoints Identify the Subproblem
Interval DP
Assign an answer to each contiguous interval and solve shorter ranges first. For adjacent merge cost, try every final split and add the interval total exactly once.
Recognize it when Operations preserve adjacency and eventually combine or resolve a contiguous range.
Checking your account…
Interval DP Code Labs
Let Endpoints Identify the Subproblem
Interval DP applies when a contiguous range can be resolved through smaller contiguous ranges. In this merge Lab, dp[left][right] means the minimum cost to reduce the inclusive range to one group. A singleton is already one group and needs no merge, so its cost is zero; empty and singleton input return zero overall.
Fill Shorter Ranges before Their Consumers
The first Lab exposes the evaluation order. Length-one intervals come first, then length two, and so on. Every proper child interval is shorter than its parent, making the required values final before the parent reads them. Increasing left alone would not establish that guarantee.
Generate Interval DP Fill Order
Reference
def interval_order(n):
return [[left,left+length-1] for length in range(1,n+1) for left in range(n-length+1)]
Practice
Implement interval_order(n). Return [left,right] inclusive intervals ordered by increasing length from 1 through n.
Public tests
Visit dependencies before larger intervals
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Generate Interval DP Fill Order
def interval_order(n):
return [[left,left+length-1] for length in range(1,n+1) for left in range(n-length+1)]
Reason Backward from the Last Merge
Immediately before the final merge of [left,right], two adjacent groups remain. Some split k divides them into [left,k] and [k+1,right]. Their best construction costs are already solved, and the final merge adds the sum of the entire interval. Trying every k covers every possible final merge tree, so their minimum is globally optimal.
Compute Minimum Interval Merge Cost
Reference
def minimum_merge_cost(values):
n=len(values)
if n<2:return 0
prefix=[0]
for value in values:prefix.append(prefix[-1]+value)
dp=[[0]*n for _ in range(n)]
for length in range(2,n+1):
for left in range(n-length+1):
right=left+length-1;total=prefix[right+1]-prefix[left]
dp[left][right]=min(dp[left][split]+dp[split+1][right]+total for split in range(left,right))
return dp[0][n-1]
Practice
Implement minimum_merge_cost(values). Merging adjacent groups costs their total; return minimum cost to merge all values.
Public tests
Try every final split
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Compute Minimum Interval Merge Cost
def minimum_merge_cost(values):
n=len(values)
if n<2:return 0
prefix=[0]
for value in values:prefix.append(prefix[-1]+value)
dp=[[0]*n for _ in range(n)]
for length in range(2,n+1):
for left in range(n-length+1):
right=left+length-1;total=prefix[right+1]-prefix[left]
dp[left][right]=min(dp[left][split]+dp[split+1][right]+total for split in range(left,right))
return dp[0][n-1]
Compare Both Final Splits of Three Groups
Predict minimum_merge_cost([3,1,2]). The final cost depends on which adjacent pair is merged first, even though the final total weight is always 6.
Step
Executed statement
State
Why
1
prefix.append(prefix[-1]+value)
prefix=[0,3,4,6]
The leading zero makes every inclusive total a boundary subtraction.
2
dp=[[0]*n for _ in range(n)]
dp[0][0]=dp[1][1]=dp[2][2]=0
Singleton groups need no operation, and table rows are independent.
3
dp[left][right]=min(dp[left][split]+dp[split+1][right]+total for split in range(left,right))
length=2; dp[0][1]=4; dp[1][2]=3
Each two-group interval has one final split and pays its pair total.
All possible final adjacent partitions are compared, rather than choosing one locally.
6
return dp[0][n-1]
return=9
The target cell solves the entire input range.
Print
Output
print(minimum_merge_cost([3,1,2]))
9
The split range excludes right; otherwise the right child is empty and indexed beyond the table at the boundary. Prefix totals use the half-open subtraction prefix[right+1]-prefix[left] for this inclusive state. Computing that aggregate once per state keeps it out of the split loop.
Explain the Interval Choice in an Interview
This example is one interval recurrence, not a formula for every interval problem. Other contracts may choose the last removed item or paired endpoints instead of a final binary merge. Name the state and prove that its last choice leaves smaller independent ranges. The merge recurrence has O(n²) states and O(n) splits per state, hence O(n³) time and O(n²) table space. Prefix sums accelerate each range total but do not replace the decision table; greedy adjacent merging needs a separate correctness proof.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Interval DP: best split of a range
Short ranges first; try every last split; keep the best.
The answer for a range i..j comes from combining two smaller ranges, and you must choose where to split.
Trigger words
burst balloons
merge stones
matrix chain
split point i..j
range dp
def matrix_chain_cost(dims): # matrix i has shape dims[i] x dims[i + 1]
n = len(dims) - 1 # number of matrices
if n < 1:
return 0
dp = [[0] * n for _ in range(n)] # dp[i][j] = cheapest cost to multiply matrices i..j
for length in range(2, n + 1): # shorter ranges first
for i in range(n - length + 1):
j = i + length - 1
best = float("inf")
for k in range(i, j): # the last multiplication joins i..k and k + 1..j
cost = dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
best = min(best, cost)
dp[i][j] = best
return dp[0][n - 1]
Spot it when
'Merge adjacent piles', 'burst balloons', 'best order to multiply'.
n is a few hundred, so O(n^3) is fine.
Remember
Fill by length so both halves of every split are already known.
Three nested loops (length, start, split): O(n^3) time, O(n^2) space.
How problems bend it
Merge adjacent piles: The last merge of a range costs the range's total, which prefix sums give in O(1).
Burst balloons: Pad the list with 1 at both ends; k is the last balloon burst inside the open range (i, j), so add nums[i] * nums[k] * nums[j].
Python Version Note
Python 3.11+
The table uses independent Python rows, avoiding aliasing between different left boundaries.