Sub topic 14
Circular Sequences by Doubling the Array
This chapter assumes you already know the linear stone-merging DP from the previous chapters. That means the state dp[i][j] over an inclusive range, filling the table by increasing interval length, and using prefix sums to get interval totals in O(1). Here the sequence is arranged in a circle, so the last element sits next to the first.
What Changes When the Sequence Is a Circle
In the linear problem, piles[0] and piles[n-1] are never adjacent. Every merge joins two neighboring blocks, and the leftmost and rightmost piles can meet only at the very end, through everything in between.
In a circle, piles[n-1] and piles[0] are neighbors. A merge order can start by combining them. No linear interval [i, j] with i <= j describes the block "last pile plus first pile", so the linear table cannot express that order.
Take the piles [1, 9, 9, 1] arranged in a circle. The linear DP returns 40. In the circle, the two piles of size 1 are adjacent:
- Merge 1 + 1 to get a pile of 2, costing 2.
- Merge 2 + 9 to get 11, costing 11.
- Merge 11 + 9 to get 20, costing 20.
The total is 33, which no linear merge order can reach.
The Key Observation: Some Boundary Is Never Crossed Early
A circle of n piles has n boundaries between neighbors. Each merge joins two adjacent blocks across one boundary. After n - 2 merges, two blocks remain, and together they cover the whole circle. These two blocks touch at two boundaries. The final merge joins them, and you can treat either of those two boundaries as the place where the circle was cut.
So every merge order on the circle corresponds to a merge order on some linear rotation: cut the circle at one boundary and lay the piles out in a line starting just after the cut. The circular optimum is therefore the minimum, over all n cut positions, of the linear optimum for that rotation.
The naive approach runs the linear O(n^3) DP once per rotation. That totals O(n^4) and repeats almost all of the work, because neighboring rotations share most of their subintervals.
Doubling the Array
Concatenate the sequence with itself: a = piles + piles. Every rotation of the circle is now a contiguous window of length n in a:
| Start `i` | Window `a[i..i+n-1]` for `[1, 9, 9, 1]` |
|---|---|
| 0 | `1, 9, 9, 1` |
| 1 | `9, 9, 1, 1` |
| 2 | `9, 1, 1, 9` |
| 3 | `1, 1, 9, 9` |
Run the ordinary interval DP on a, but only for lengths up to n. A single table then holds the linear answer for every rotation. Windows that overlap share their sub-intervals, so each sub-interval is computed once.
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):
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, 9, 9, 1])) # 33Only three things differ from the linear version:
- The prefix sums are built over the doubled array
a, soprefix[j + 1] - prefix[i]gives correct totals for windows that wrap around. - The length loop stops at
n. Longer intervals would count some piles twice, and nothing reads them. - The answer is the minimum of
dp[i][i + n - 1]over thenstart positions. It is notdp[0][n - 1].
Checking It Against Brute Force
When you adapt a DP to a new shape, test it against a slow but obviously correct version. The rotation brute force follows directly from the cut argument above.
import random
def min_merge_cost(piles):
n = len(piles)
if n <= 1:
return 0
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
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 + prefix[j + 1] - prefix[i]
return dp[0][n - 1]
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):
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))
def brute_circular(piles):
n = len(piles)
return min(min_merge_cost(piles[r:] + piles[:r]) for r in range(n))
random.seed(1)
for _ in range(300):
size = random.randint(1, 7)
piles = [random.randint(1, 20) for _ in range(size)]
assert min_merge_cost_circular(piles) == brute_circular(piles), piles
print("all tests passed")
print(min_merge_cost([1, 9, 9, 1]), min_merge_cost_circular([1, 9, 9, 1])) # 40 33Cost Analysis
For each length L from 2 to n, the doubled DP visits about 2n - L + 1 intervals and tries L - 1 splits for each one:
| Approach | Transitions (leading term) | Space |
|---|---|---|
| Linear DP, one sequence | about n^3 / 6 | O(n^2) |
| Linear DP on each of n rotations | about n^4 / 6 | O(n^2) reused |
| Doubled array, lengths up to n | about 2n^3 / 3 | O(n^2) with a (2n) x (2n) table |
Doubling keeps the circular problem at O(n^3), about four times the work of a single linear run. The (2n) x (2n) table holds four times as many cells as the linear one, and only cells with j - i < n are ever written.
Common Mistakes
- Reading the wrong cell. Returning
dp[0][n - 1]gives only the rotation that starts at index 0, which is the linear answer. Returningdp[0][2n - 1]covers every pile twice. - Running lengths past
n. Correctness survives because those cells are never read, but the work grows to O(8n^3/6) and the table holds meaningless values that can mislead you while debugging. - Prefix sums over the original array. A window such as
a[3..6]then indexes past the end, or wraps with the wrong total. - Forgetting
n = 1. A single pile needs no merges. The guard returns 0 before theminover an empty range of splits can fail.
Variant: Circular Chains with Boundary Values
Some circular problems attach values to boundaries rather than to elements. In the energy necklace problem, bead t has head mark h[t] and tail mark h[t+1 mod n], and merging adjacent blocks [i..k] and [k+1..j] releases h[i] * h[k+1] * h[j+1]. This is matrix chain multiplication on a circle. Double the mark array to length 2n (append one more mark if you index h[j+1] at j = 2n - 1) and take the maximum of dp[i][i + n - 1]. The only new detail is the extra boundary index at the window's right end.
Exercise
For the circular piles [1, 9, 9, 1], list each start position i from 0 to 3 with the value dp[i][i+3] in the doubled table, and identify which window gives the answer 33.
Show answer
The windows are i=0: [1,9,9,1] with cost 40, i=1: [9,9,1,1] with cost 33, i=2: [9,1,1,9] with cost 33, and i=3: [1,1,9,9] with cost 33. The minimum is 33. Every window except i=0 places the two piles of size 1 next to each other, so they can be merged first for a cost of 2.
Exercise
Why does the length loop stop at n, and what would a cell with j - i + 1 = n + 1 represent?
Show answer
A rotation of the circle contains exactly n piles, so no valid subproblem is longer than n. An interval of length n + 1 includes one pile twice, for example a[0] and a[n], which are the same physical pile. It does not describe any real state, and computing it only wastes time.
Exercise
Change minmergecost_circular so it returns the maximum total merge cost instead of the minimum. Which lines change?
Show answer
Change the inner min over k to max, and change the final min over start positions to max. The doubling, the prefix sums, and the length bound stay the same. For [1, 9, 9, 1] the maximum is 9+9=18, then 18+1=19, then 19+1=20, giving 57.