Sub topic 11
Constant-Time Interval Costs with Prefix Sums
Many interval DP recurrences add a cost that depends on the whole range: the total weight of the piles being merged, the sum of the values in a segment, or the product of the sums of the two halves. If you compute that cost with a loop every time you need it, you add a factor of n to the running time. Prefix sums remove that factor. After O(n) preprocessing, the sum of any contiguous range takes one subtraction.
This chapter assumes you know the split-point recurrence, the length-ordered filling of dp[i][j], and the O(n^3) cost analysis from earlier chapters. It sets up the cost machinery that the next chapter, on merging adjacent piles, uses directly.
The Problem: Range Costs Inside the DP Loops
Here is a typical split-point recurrence with a range cost:
dp[i][j] = min over k in [i, j) of ( dp[i][k] + dp[k+1][j] ) + cost(i, j)There are about n^2/2 states, and each one tries up to n splits. If cost(i, j) is sum(a[i:j+1]), each call takes O(j - i + 1) time. Where that call sits in the loops decides how much it costs you.
| Where the O(n) cost is computed | Total time |
|---|---|
| Inside the `k` loop (recomputed for every split) | O(n^4) |
| Once per state, outside the `k` loop | O(n^3) |
| Once per state, via prefix sums | O(n^3), with a smaller constant |
| Cost depends on `k`, via prefix sums | O(n^3) instead of O(n^4) |
| Under Knuth's optimization (amortized O(1) splits per state) | O(n^2) only if cost is O(1) |
The table shows a subtlety. If the cost depends only on (i, j) and you compute it once per state, a naive sum costs no more asymptotically than the DP itself. Prefix sums become necessary in two cases:
- The cost depends on the split point
k, so it must be evaluated inside the inner loop. - You have reduced the transitions to amortized O(1) per state, as Knuth's optimization does in the final chapter. An O(n) cost per state would then dominate.
Use prefix sums anyway. They are short, easy to check, and they keep the cost term from becoming the bottleneck when you later optimize the DP.
Building and Querying a Prefix Array
A prefix array stores running totals. Define prefix[t] as the sum of the first t elements, a[0] + ... + a[t-1], with prefix[0] = 0. The array has length n + 1.
The sum of the inclusive range a[i..j] is then:
sum(i, j) = prefix[j + 1] - prefix[i]prefix[j + 1] covers a[0..j], and subtracting prefix[i] removes a[0..i-1].
from itertools import accumulate
def build_prefix(a):
# prefix[t] = a[0] + ... + a[t - 1]; prefix[0] = 0
prefix = [0] * (len(a) + 1)
for i, x in enumerate(a):
prefix[i + 1] = prefix[i] + x
return prefix
def range_sum(prefix, i, j):
# Sum of a[i..j], both ends inclusive.
return prefix[j + 1] - prefix[i]
a = [4, 1, 1, 4]
p = build_prefix(a)
print(p) # [0, 4, 5, 6, 10]
print(range_sum(p, 1, 2)) # 2
print(range_sum(p, 0, 3)) # 10
print(range_sum(p, 2, 2)) # 1
# The standard library builds the same array.
print(list(accumulate(a, initial=0))) # [0, 4, 5, 6, 10]Matching the Formula to Your Bound Convention
Earlier chapters stressed choosing inclusive or exclusive bounds for dp[i][j] and sticking to that choice. The prefix formula has to match it.
| Interval convention | Range covered | Sum formula |
|---|---|---|
| Inclusive `[i, j]` | `a[i]` through `a[j]` | `prefix[j + 1] - prefix[i]` |
| Half-open `[i, j)` | `a[i]` through `a[j - 1]` | `prefix[j] - prefix[i]` |
| Open `(i, j)` (burst-balloon style) | `a[i + 1]` through `a[j - 1]` | `prefix[j] - prefix[i + 1]` |
Using Prefix Sums in an Interval DP
The skeleton below follows the length-ordered fill from earlier chapters. Its cost term does not depend on k, so it is added once, after the minimum is found.
def interval_dp_with_range_cost(a):
n = len(a)
if n <= 1:
return 0
prefix = build_prefix(a)
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
best = min(dp[i][k] + dp[k + 1][j] for k in range(i, j))
dp[i][j] = best + range_sum(prefix, i, j)
return dp[0][n - 1]
print(interval_dp_with_range_cost([4, 1, 1, 4])) # 20This is the recurrence for merging adjacent piles. The next chapter explains why it is correct. The point here is mechanical: range_sum is O(1), and because it does not depend on k it is evaluated outside the min.
When the Cost Depends on the Split
Suppose that combining the left part a[i..k] with the right part a[k+1..j] costs the product of their totals. Now the cost changes with k and must be computed inside the inner loop. A naive sum would make the algorithm O(n^4). With prefix sums it stays O(n^3).
def min_product_merge(a):
n = len(a)
if n <= 1:
return 0
prefix = build_prefix(a)
INF = float("inf")
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = INF
for k in range(i, j):
left = range_sum(prefix, i, k)
right = range_sum(prefix, k + 1, j)
cost = dp[i][k] + dp[k + 1][j] + left * right
if cost < dp[i][j]:
dp[i][j] = cost
return dp[0][n - 1]
def min_product_merge_naive(a):
# Reference version: recomputes sums with slicing (O(n^4)).
n = len(a)
if n <= 1:
return 0
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = min(
dp[i][k] + dp[k + 1][j] + sum(a[i:k + 1]) * sum(a[k + 1:j + 1])
for k in range(i, j)
)
return dp[0][n - 1]
import random
for _ in range(200):
arr = [random.randint(0, 9) for _ in range(random.randint(0, 8))]
assert min_product_merge(arr) == min_product_merge_naive(arr)
print(min_product_merge([1, 2, 3])) # 11Comparing the fast version against a slow version you can trust, on random inputs, is the quickest way to catch an off-by-one in the prefix indexing.
Costs Beyond Plain Sums
Prefix sums work for any operation that can be undone, meaning you can subtract out the part before i. For other operations you need another O(1) method.
| Range cost | O(1) technique |
|---|---|
| Sum of values | Prefix sums |
| Sum of squares, or any `sum f(a[t])` | Prefix sums of `f(a[t])` |
| Weighted sum `sum t * a[t]` | Prefix sums of `t * a[t]` |
| XOR of values | Prefix XOR: `px[j + 1] ^ px[i]` |
| Product of values | Risky: division fails on zeros, and modular inverses need a prime modulus |
| Max or min | Precompute an O(n^2) table incrementally, or use a sparse table |
Max and min cannot be undone by subtraction. The DP already uses O(n^2) memory, though, so you can fill a full cost table in O(n^2) time by extending each range one element at a time:
def interval_max_table(a):
n = len(a)
mx = [[0] * n for _ in range(n)]
for i in range(n):
mx[i][i] = a[i]
for j in range(i + 1, n):
mx[i][j] = max(mx[i][j - 1], a[j])
return mx
mx = interval_max_table([3, 1, 5, 2])
print(mx[0][3], mx[1][3], mx[1][1]) # 5 5 1The same incremental approach works for any cost where cost(i, j) follows from cost(i, j - 1) and a[j] in O(1). It needs more memory than a prefix array but no more than the DP table.
Practical Pitfalls
- Overflow. In Python, integers do not overflow. In C++ or Java, prefix totals can exceed 32 bits even when every element fits, so use 64-bit integers for the prefix array.
- Floating-point cancellation. With float inputs,
prefix[j + 1] - prefix[i]subtracts two large numbers that are close together, which can lose precision. Use integers when you can, or scale values to integers. - Circular inputs. When you double the array for circular problems, build the prefix array over the doubled array with length
2n + 1, not over the original. - Negative values. Prefix sums handle negative numbers correctly. Any claim that the cost is monotone (needed later for Knuth's optimization) can fail once negative values appear, though.
Exercise
Your DP uses half-open intervals, where dp[i][j] covers a[i..j-1]. Using a prefix array with prefix[0] = 0 and prefix[t] = a[0] + ... + a[t-1], write the expression for the sum of the elements covered by dp[i][j], and evaluate it for a = [2, 7, 1, 8], i = 1, j = 3.
Show answer
The sum is prefix[j] - prefix[i]. The prefix array is [0, 2, 9, 10, 18], so the sum is prefix[3] - prefix[1] = 10 - 2 = 8, which equals a[1] + a[2] = 7 + 1.
Exercise
A split-point DP has n^2/2 states and up to n splits per state. Its cost term is sum(a[i..k]) + sum(a[k+1..j]), written with Python slicing inside the k loop. What is the total time, and what is it after switching to prefix sums? Then simplify the cost term itself.
Show answer
With slicing, each split costs O(n), so the total is O(n^4). With prefix sums each split costs O(1), so the total is O(n^3). The term simplifies further: sum(a[i..k]) + sum(a[k+1..j]) equals sum(a[i..j]), which does not depend on k. You can compute it once per state, outside the k loop.
Exercise
Why is "prefix products" a poor general way to get the product of a[i..j] in O(1), and what would you do instead inside an interval DP?
Show answer
Getting the product requires dividing prefixprod[j + 1] by prefixprod[i]. That fails once any earlier element is zero, because every later prefix product becomes zero. Under a modulus, division needs a modular inverse, which exists only for values coprime to the modulus. Inside an interval DP it is safer to precompute prod[i][j] = prod[i][j - 1] * a[j] in O(n^2) time and space, which fits within the DP's own budget.