Sub topic 14
Circular Sequences by Doubling the Array
This chapter assumes you know the linear stone-merging DP from the earlier chapter, where dp[i][j] is the minimum cost to merge piles i..j into one pile. It also assumes you know prefix sums for interval totals and the habit of filling the table by increasing interval length.
When the Ends Touch
Some problems put the sequence on a circle. In circular stone merging, piles sit around a ring, and the last pile is adjacent to the first. Any two neighbors can merge, including the pair that wraps around the ring.
The linear DP cannot see that wrap-around pair. Take piles [1, 4, 4, 1]:
| Model | Best merge order | Total cost |
|---|---|---|
| Linear | (1+4), (4+1), then 5+5 | 5 + 5 + 10 = 20 |
| Circular | (1+1) across the wrap, then 2+4, then 6+4 | 2 + 6 + 10 = 18 |
The cheaper plan merges the two 1s first. Those 1s are only adjacent on the circle.
The Doubling Trick
You can cut a circle of n items at any of n places. Each cut gives a linear sequence, which is a rotation of the original. The final merge always joins two arcs that together cover the ring, so every merge plan works inside one of these rotations.
You could run the linear DP once per rotation, but that costs O(n^4). Instead, write the array twice: a = piles + piles. Every rotation then appears as a contiguous window of length n:
- rotation starting at 0 is
a[0..n-1] - rotation starting at 1 is
a[1..n] - ...
- rotation starting at
n-1isa[n-1..2n-2]
One interval DP over a fills dp[i][j] for every interval up to length n. The windows overlap, so their shorter subintervals are shared. The answer is the minimum of dp[i][i + n - 1] over i in 0..n-1.
Implementation
def min_merge_cost_circular(piles):
n = len(piles)
if n <= 1:
return 0
a = piles + piles
m = 2 * n
prefix = [0] * (m + 1)
for i, p in enumerate(a):
prefix[i + 1] = prefix[i] + p
dp = [[0] * m for _ in range(m)]
for length in range(2, n + 1): # never longer than n
for i in range(m - 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 + prefix[j + 1] - prefix[i]
return min(dp[i][i + n - 1] for i in range(n))
print(min_merge_cost_circular([1, 4, 4, 1])) # 18Cost
The table has 2n × 2n cells, but only intervals of length at most n get filled. That is about 2n · n states with up to n splits each, so time stays O(n^3), about twice the linear version's work. Space is O(n^2) with a constant four times larger. If memory is tight, you can index dp[i][length] instead of dp[i][j].
Common Errors
- Taking
dp[0][2n-1]as the answer. That interval covers two copies of every pile. Take the minimum over thenwindows of lengthn. - Building prefix sums over the original array only. Prefix sums must cover the doubled array, or
prefix[j + 1]runs out of range for windows that wrap. - Missing the
n <= 1guard. For a single pile, the length loop never runs, and the code returns a zero that only happens to be right. State the base case explicitly. - Doubling when the problem is not circular. Doubling only helps when the wrap-around pair is truly adjacent. On a linear problem it can return a cost lower than any real plan.
Exercise
For circular piles [3, 1, 2], what does minmergecost_circular return, and which rotation achieves it?
Show answer
It returns 9. Every rotation costs the same: merge the two smallest adjacent piles 1 and 2 (cost 3), then merge 3 with 3 (cost 6), for 3 + 6 = 9. With three piles on a ring, every pair is adjacent, so all three windows [3,1,2], [1,2,3], and [2,3,1] give 9.
Exercise
Why does the length loop stop at n and not at 2n - 1?
Show answer
Any window longer than n contains at least one pile twice. Its dp value would count merging that pile two times, which matches no real plan on the ring. Windows of length n are exactly the rotations, so they are the longest intervals the answer needs.