Solve every range from short to long by trying each split point: games, triangulation, cuts and balloons.
You work on a platform that stores build logs in shards laid out in a row. To archive them, the system merges two neighbouring shards into one. A merge copies every byte of both shards, so its cost is their combined size.
Only neighbours can merge, and the merged shard stays in the same place. Your team lead says: "In which order should we merge the five shards, of sizes 5, 2, 7, 3 and 6 units, to copy the least in total?"
Start with the first four shards: 5, 2, 7 and 3 units. Five merge orders exist, and you can list them all. The cost of an order is the sum of the sizes of every merge in it.
| Order | The merges | Total cost |
|---|---|---|
| 1 | 5 + (2 + (7 + 3)) | 39 |
| 2 | 5 + ((2 + 7) + 3) | 38 |
| 3 | (5 + 2) and (7 + 3), then both | 34 |
| 4 | (5 + (2 + 7)) + 3 | 40 |
| 5 | ((5 + 2) + 7) + 3 | 38 |
The best total is 34: merge 5 with 2 (cost 7) and 7 with 3 (cost 10), then merge the two results (cost 17). Different orders give different totals, so the order matters.
The first attempt is correct. Choose where the last merge happens, so the row splits into a left part and a right part. Merge each part the same way, add the size of the whole row for the last merge, and keep the least.
def merge_every_order(sizes, i, j):
if i == j:
return 0
best = None
for k in range(i, j):
total = merge_every_order(sizes, i, k) + merge_every_order(sizes, k + 1, j)
if best is None or total < best:
best = total
return best + sum(sizes[i:j + 1])Now check the growth. The number of merge orders for n shards is a Catalan number. Counting by running code gives these values.
| Shards | Merge orders |
|---|---|
| 4 | 5 |
| 5 | 14 |
| 10 | 4,862 |
| 15 | 2,674,440 |
| 20 | 1,767,263,190 |
Look at what the first attempt repeats. Run on 12 shards, it makes 177,147 calls, and 10 shards make 19,683. Many calls ask for the same range again, for example shards 3 to 6. The best cost of merging a range does not depend on what happens outside it.
In a knockout bracket the final splits the row of teams in two. Merging shards has the same shape: the last merge splits the row.
In a knockout bracket for a row of teams, the final splits the row into a left half and a right half. Each half is a smaller tournament with its own final.
To plan the whole bracket you plan every smaller bracket first, short ones before long ones. Merging shards works the same way. The last merge splits the row in two, and each side is a smaller problem of the same kind.
An interval DP table holds one answer for every stretch of the row. A range is a stretch of neighbouring items from i to j, and the table is filled from short ranges to long ones.
Predict what happens
Q The best cost to merge shards 3 to 6 is known. Does it change if shards 0 to 2 are merged in a different order first?
Answer: B
A range is merged using only its own shards, so its best cost is one fixed number. That is why a table with one entry for each range is enough.
An interval table has one cell for each range [i, j] of the row. A row of n items has n × (n + 1) / 2 ranges. Each cell answers one question: what is the best result for the items from i to j?
Take the sizes 5, 2, 7, 3 and 6. Let cost[i][j] be the least cost to merge shards i to j into one. A single shard costs 0, because it is already one.
A longer range is solved by trying every split point k. The last merge joins shards i to k with shards k + 1 to j. Its cost is the total size of the whole range, because every byte is copied once more.
For the whole row, shards 0 to 4, there are four split points. The total size of the row is 23, and the table below is filled before this step.
Split k |
Left part | Right part | Left + right + 23 |
|---|---|---|---|
| 0 | cost[0][0] = 0 |
cost[1][4] = 36 |
59 |
| 1 | cost[0][1] = 7 |
cost[2][4] = 25 |
55 |
| 2 | cost[0][2] = 21 |
cost[3][4] = 9 |
53 |
| 3 | cost[0][3] = 34 |
cost[4][4] = 0 |
57 |
The least is 53, at k = 2. This loop is the heart of interval DP. For every range you try every split and keep the best.
To solve a range, try every split point k, add the best answers of the two parts, and keep the least.
Which cells does a range read? A range [i, j] reads [i, k] and [k + 1, j], and both are shorter than [i, j]. So fill every range of length 1 first, then every range of length 2, then length 3, up to the whole row.
| Length | Ranges (i, j) and their cost |
|---|---|
| 1 | all five single shards: 0 |
| 2 | (0, 1): 7, (1, 2): 9, (2, 3): 10, (3, 4): 9 |
| 3 | (0, 2): 21, (1, 3): 21, (2, 4): 25 |
| 4 | (0, 3): 34, (1, 4): 36 |
| 5 | (0, 4): 53 |
The last row holds 53, the answer. At each length, every range finds the shorter ranges it needs already filled.
Exercise · Predict the output: Three shards, three cells. The table is filled by length for the shard sizes 2, 3 and 1. What does it print for cost[0][1], cost[1][2] and cost[0][2]?
sizes = [2, 3, 1]
n = len(sizes)
cost = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
total = sum(sizes[i:j + 1])
cost[i][j] = min(cost[i][k] + cost[k + 1][j] for k in range(i, j)) + total
print(cost[0][1], cost[1][2], cost[0][2])Fill every range of length one, then two, then three, so each range finds the shorter ranges it reads already filled.
The step-through below is a grid of routes, not ranges, because the site has no picture for ranges. It follows the same rule: a cell is filled only after the cells it reads.
Step by step: Routes on an open grid, row by row. The animated player loads in your browser.
A habit from grid tables is to fill row by row: i from 0 upwards, and j from i + 1 to the end. Here that order fails. The range [0, 4] reads [1, 4], which belongs to a row that has not been filled yet.
Run the same code with the loops in that order on the sizes 5, 2, 7, 3 and 6. It returns 23, and the right answer is 53. The cells it reads from later rows are still 0, so every merge looks as if its right part were free.
The loop bounds are not a detail. Fill by length, so that both shorter ranges exist when a range reads them.
The step engine on the site draws tables for routes and for common letters, and it has no picture for ranges. These tables follow the same rule as interval tables: a cell is filled only after every cell it reads. Step through them and watch which cells light up when a new cell is filled.
Try these three, in order:
For ranges, remember the difference: the cell for [i, j] reads cells to its left in row i and below it in column j. Those are shorter ranges, so the fill goes diagonal by diagonal.
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Predict what happens
Q A table cell for the range [0, 4] reads [0, 2] and [3, 4]. Which cells are guaranteed to be filled when the fill goes by length?
Answer: B
Filling by length means that when the length-5 range is reached, every range of length 1 to 4 is done. Both of the parts it reads are shorter, so they are ready.
Interval DP has the same three parts as the earlier lessons, now with a range for a state.
cost[i][j] is the least cost to merge shards i to j into one.k from i to j - 1. The cost is cost[i][k] + cost[k + 1][j], plus the total size of shards i to j. Keep the least.cost[0][n - 1].A range is filled only after every shorter range inside it is filled. So each cell holds the best value for its own range, built by trying every way to split it.
Why is it right? A single shard is right by definition. Any way to merge a longer range ends with one last merge that joins a left part and a right part. Each part is merged on its own, so its best cost is a correct smaller answer.
Trying every k covers every possible last merge.
Exercise · Break it: Find the input where merging the cheapest pair first loses. This function always merges the adjacent pair with the smallest total, until one shard is left. Find a row of shard sizes where it copies more than the best plan.
def greedy_merge_cost(sizes):
items = list(sizes)
total = 0
while len(items) > 1:
k = 0
for t in range(len(items) - 1):
if items[t] + items[t + 1] < items[k] + items[k + 1]:
k = t
merged = items[k] + items[k + 1]
total += merged
items[k:k + 2] = [merged]
return totalHere is the table as code. Read the markers beside the explanation above.
def least_merge_cost(sizes):
n = len(sizes)
# [1] prefix[k] is the total of the first k shards, so the total of any range is one subtraction.
prefix = [0] * (n + 1)
for k in range(n):
prefix[k + 1] = prefix[k] + sizes[k]
# [2] cost[i][j] is the least cost to merge shards i to j into one. A single shard is already one, so it costs 0.
cost = [[0] * n for _ in range(n)]
# [3] Fill by length, so both shorter ranges that a range reads are ready.
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
best = None
for k in range(i, j):
# [4] The last merge joins shards i to k with shards k + 1 to j. Try every k and keep the least.
total = cost[i][k] + cost[k + 1][j]
if best is None or total < best:
best = total
cost[i][j] = best + prefix[j + 1] - prefix[i]
# [5] The whole row is the range from the first shard to the last.
return cost[0][n - 1]public int leastMergeCost(int[] sizes) {
int n = sizes.length;
// [1] prefix[k] is the total of the first k shards, so the total of any range is one subtraction.
int[] prefix = new int[n + 1];
for (int k = 0; k < n; k++) {
prefix[k + 1] = prefix[k] + sizes[k];
}
// [2] cost[i][j] is the least cost to merge shards i to j into one. A single shard is already one, so it costs 0.
int[][] cost = new int[n][n];
// [3] Fill by length, so both shorter ranges that a range reads are ready.
for (int length = 2; length <= n; length++) {
for (int i = 0; i + length <= n; i++) {
int j = i + length - 1;
int best = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
// [4] The last merge joins shards i to k with shards k + 1 to j. Try every k and keep the least.
int total = cost[i][k] + cost[k + 1][j];
if (total < best) {
best = total;
}
}
cost[i][j] = best + prefix[j + 1] - prefix[i];
}
}
// [5] The whole row is the range from the first shard to the last.
return cost[0][n - 1];
}int leastMergeCost(vector<int> sizes) {
int n = sizes.size();
// [1] prefix[k] is the total of the first k shards, so the total of any range is one subtraction.
vector<int> prefix(n + 1, 0);
for (int k = 0; k < n; k++) {
prefix[k + 1] = prefix[k] + sizes[k];
}
// [2] cost[i][j] is the least cost to merge shards i to j into one. A single shard is already one, so it costs 0.
vector<vector<int>> cost(n, vector<int>(n, 0));
// [3] Fill by length, so both shorter ranges that a range reads are ready.
for (int length = 2; length <= n; length++) {
for (int i = 0; i + length <= n; i++) {
int j = i + length - 1;
int best = INT_MAX;
for (int k = i; k < j; k++) {
// [4] The last merge joins shards i to k with shards k + 1 to j. Try every k and keep the least.
int total = cost[i][k] + cost[k + 1][j];
if (total < best) {
best = total;
}
}
cost[i][j] = best + prefix[j + 1] - prefix[i];
}
}
// [5] The whole row is the range from the first shard to the last.
return cost[0][n - 1];
}function leastMergeCost(sizes) {
const n = sizes.length;
// [1] prefix[k] is the total of the first k shards, so the total of any range is one subtraction.
const prefix = new Array(n + 1).fill(0);
for (let k = 0; k < n; k++) {
prefix[k + 1] = prefix[k] + sizes[k];
}
// [2] cost[i][j] is the least cost to merge shards i to j into one. A single shard is already one, so it costs 0.
const cost = Array.from({ length: n }, () => new Array(n).fill(0));
// [3] Fill by length, so both shorter ranges that a range reads are ready.
for (let length = 2; length <= n; length++) {
for (let i = 0; i + length <= n; i++) {
const j = i + length - 1;
let best = Infinity;
for (let k = i; k < j; k++) {
// [4] The last merge joins shards i to k with shards k + 1 to j. Try every k and keep the least.
const total = cost[i][k] + cost[k + 1][j];
if (total < best) {
best = total;
}
}
cost[i][j] = best + prefix[j + 1] - prefix[i];
}
}
// [5] The whole row is the range from the first shard to the last.
return cost[0][n - 1];
}Exercise · Find the bug: The merge that copies too little. This table returns a cost that is too small, even for two shards. Which line is wrong?
def least_merge_cost(sizes):
n = len(sizes)
prefix = [0] * (n + 1)
for k in range(n):
prefix[k + 1] = prefix[k] + sizes[k]
cost = [[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 = None
for k in range(i, j):
total = cost[i][k] + cost[k + 1][j]
if best is None or total < best:
best = total
cost[i][j] = best + prefix[j] - prefix[i]
return cost[0][n - 1]The merge example splits a range into two parts. Two more shapes cover the problems in this lesson.
| Shape | Transition | Problems |
|---|---|---|
| Split into two parts | try k, join [i, k] and [k + 1, j] or [k, j] |
merging shards, triangulation, splitting a log file at its first split |
| Choose the last item removed | try k, so its neighbours are i and j |
retiring ad slots |
| Peel one end | take i or j, then solve [i + 1, j] or [i, j - 1] |
the row game, palindromes |
All three read shorter ranges, so all three fill by length. When the first item removed changes who the neighbours are, choose the last one instead. Then the two sides cannot touch each other.
Predict what happens
Q The best way to split [i, j] has its last merge at k = 2. What do the two parts of that merge read from the table?
Answer: B
The last merge joins shards i to k with shards k + 1 to j. Both parts are smaller ranges, so they are already filled when the fill goes by length.
Predict what happens
Q In a lookup tree over sorted keys, the root is key k. Which keys end up in the left part?
Answer: B
A search tree keeps keys in order. Keys smaller than the root go left and larger keys go right, so each side is a range of the sorted keys.
Now write it yourself. The lab has one function, least_search_cost(counts). A lookup service keeps n sorted keys, and counts[i] says how often key i is requested. The keys form a search tree: one root, a left tree of smaller keys and a right tree of larger keys.
A request for a key costs one step per level it passes, and the root is level 1. The total cost is the sum of count × level over all keys. You return the least total over all possible trees.
Here is a small run on the counts [3, 1, 2]. Each range holds its own total once the root is chosen, because every key in it goes one level deeper.
| Length | Keys | Least cost |
|---|---|---|
| 1 | key 0, key 1, key 2 alone | 3, 1, 2 |
| 2 | keys 0 to 1, keys 1 to 2 | 5, 4 |
| 3 | keys 0 to 2 | 10 |
The answer is 10: key 0 is the root, key 2 is below it, and key 1 below that, giving 3 × 1 + 2 × 2 + 1 × 3.
Three rules keep it correct:
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
The cost of an interval table is the number of ranges times the number of split points for each.
| Question | Split into two parts, or choose the last | Peel one end |
|---|---|---|
| Time | O(n³): about n²/2 ranges, up to n splits each | O(n²): 2 reads for each range |
| Memory | O(n²) for the table | O(n²), or O(n) if only the last length is kept |
| Split checks for 200 items | 1,333,300 | 20,100 ranges, 2 reads each |
| What to keep | The whole table, to recover the best split | The whole table, or two lengths |
Here are the counts of split checks, found by running the code on rows of equal items.
| Items | Split checks | Ranges |
|---|---|---|
| 5 | 20 | 15 |
| 10 | 165 | 55 |
| 20 | 1,330 | 210 |
| 50 | 20,825 | 1,275 |
| 100 | 166,650 | 5,050 |
| 200 | 1,333,300 | 20,100 |
A cubic cost is fine up to a few hundred items and too slow at a few thousand. When the limit is 200 or 500 items, think interval DP.
Use an interval table when the best answer for a stretch of neighbouring items depends on shorter stretches inside it. Words such as "merge adjacent", "cut at chosen points", "remove one at a time" and "take from either end" are the hint.
Write the state as one sentence about a range [i, j] first. Then decide the shape: a split, the last item removed, or an end peeled. The order is always by length.
Do not use an interval table when the items you combine need not be next to each other. A subsequence problem on two strings reads two prefixes, which is a different table. Choosing any subset of items under a limit is a knapsack.
Do not use it when n is in the tens of thousands. Cubic work is too slow. Look for a greedy rule or a faster method instead.
A fill with for i in range(n): for j in range(i + 1, n) reads cost[k + 1][j] before row k + 1 exists, so it reads 0. For sizes = [5, 2, 7, 3, 6] it returns 23, and the answer is 53. Fill by length.
Filling row by row reads cells from later rows that are still zero, so the answer is wrong. Fill by length.
The loop for k in range(i, j - 1) never tries the last split, k = j - 1. For sizes = [1, 1, 2] it returns 7, and the answer is 6. The loop for a range [i, j] must run k from i to j - 1.
The rule "always merge the adjacent pair with the smallest total" feels natural. For sizes = [3, 4, 2, 5] it merges 4 and 2 first and costs 29, and the answer is 28. A cheap merge now can make a larger part that every later merge copies again. Only the table tries every split.
Splitting every range at its middle, k = (i + j) // 2, builds a balanced plan, but not the best one. For sizes = [2, 1, 1] it costs 7, and the answer is 6. The best split depends on the sizes, so try every k.
[i, j]. Each cell holds the best answer for that range.Explain the three questions in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Interval DP
Q1/10 What does the cell cost[i][j] hold in the merge table?
Answer: B
Each cell answers one question about a range: the least cost to merge the shards from i to j into one. A range of one shard costs 0.
Q2/10 A table over ranges is filled row by row, with i from 0 upwards. What goes wrong?
Answer: A
A range [i, j] reads [k + 1, j], which sits in a later row. Row by row, that cell is still 0, and the error spreads. Filling by length makes every shorter range ready.
Q3/10 The last merge of shards i to j joins shards i to k with shards k + 1 to j. Which two cells does it read?
Answer: C
The two parts are the ranges on either side of the split. Both are shorter than the whole range, so both are filled earlier when the fill goes by length.
Q4/10 For 10 shards of equal size, running the table checks how many split points in all?
Answer: D
Counting split points over all ranges by running code gives 165 for 10 shards and 1,333,300 for 200. The count grows like n cubed over 6, not like a factorial.
Q5/10 What are the time and the memory of the interval table with a split loop?
Answer: B
There are about n²/2 ranges, each trying up to n splits, so the time is cubic. The table has one number per range, so the memory is square.
Q6/10 Which loop tries every split point for the range [i, j]?
Answer: C
The last merge can join [i, k] with [k + 1, j] for k from i to j - 1. Stopping one short skips the split k = j - 1. For sizes [1, 1, 2] that makes the answer 7 instead of 6.
Q7/10 In the ad slots problem, the first slot retired changes who the neighbours are. How does the table avoid this?
Answer: A
If k is the last item removed in a range, its neighbours are i and j when it goes, and the two sides never touch. So the two smaller ranges are independent.
Q8/10 The rule always merge the adjacent pair with the smallest total gives 29 for sizes [3, 4, 2, 5]. The table gives 28. What does this show?
Answer: D
The table tries every split and keeps the least, so it cannot be beaten. The greedy rule looks only at the next merge, and it can create a large part that every later merge copies.
Q9/10 Which problem is not a fit for an interval table?
Answer: B
A subset need not be neighbours, so ranges do not describe it. It is a knapsack. Merging, cutting and taking from ends all act on a stretch of neighbours.
Q10/10 In the row game each player takes the first or the last post. Which cells does the cell for [i, j] read?
Answer: C
Peeling one end leaves a range one item shorter: [i + 1, j] after taking the left post, or [i, j - 1] after taking the right. Two reads for each range give O(n²) time.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.