Skip to contentKEEP THE CRAFTTHE SANCTUARY

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.

1 practice exercise3 interview problems

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.
4 right=left+length-1; total=prefix[right+1]-prefix[left] length=3; left=0; right=2; total=6 The final merge pays the full interval weight once.
5 dp[left][right]=min(dp[left][split]+dp[split+1][right]+total for split in range(left,right)) split 0 candidate=0+3+6=9; split 1 candidate=4+0+6=10; dp[0][2]=9 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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Minimize the cost of merging adjacent groupsO(n³)O(n³)There are O(n²) interval states and up to O(n) split candidates for each.

Space

O(n²) DP plus O(n) prefix totals; interval_order returns O(n²) pairs.

Assumptions

  • Prefix subtraction makes the interval total O(1); it does not remove the split loop.
  • The fill-order Lab enumerates all intervals in O(n²) time and output, not the O(n³) merge optimization.
  • The table uses independent Python rows, avoiding aliasing between different left boundaries.

Invariants Worth Saying Aloud

  1. dp[left][right] is the minimum cost to merge that inclusive interval into one group.
  2. Singletons require no merge and have cost zero.
  3. Increasing lengths complete both child intervals before any split reads them.
  4. Each final split partitions the interval into [left,split] and [split+1,right].

When To Use Or Avoid Interval DP

Use It When

  • The optimum for a range depends only on its endpoints and solved smaller ranges.
  • Every complete construction has a final split that the recurrence can enumerate.

Choose Another Tool When

  • The required groups are not contiguous, so two endpoints do not identify the full state.
  • One prefix state is sufficient; an interval table would add an unnecessary dimension.
  • A claimed greedy merge lacks a proof that its local choice preserves a global optimum.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Excluding the inclusive right value from the total

prefix[right] stops before the final value and underprices every merge of the interval.

Prevent it: Translate inclusive endpoints to prefix[right+1]-prefix[left].

Avoid

total=prefix[right]-prefix[left]

Use instead

total=prefix[right+1]-prefix[left]

Allowing the split at right itself

The split must leave two nonempty groups. At the last index, split+1 reads beyond the DP table.

Prevent it: Use range(left,right), which excludes the invalid final boundary.

Avoid

candidates=[dp[left][split]+dp[split+1][right]+total for split in range(left,right+1)]

Use instead

candidates=[dp[left][split]+dp[split+1][right]+total for split in range(left,right)]

Sharing one row across every interval start

Repeated references make writing one interval also change another row, corrupting child costs.

Prevent it: Create each mutable row with its own list construction.

Avoid

dp=[[0]*3]*3
dp[0][1]=4

Use instead

dp=[[0]*3 for _ in range(3)]
dp[0][1]=4

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.