Five hard problems that ask for the best way to split a range into smaller ranges. The move: find the one decision that makes both sides independent, then fill the table by range length.
You work on a logging service, a chat app and an ad platform. The five problems on this street come from all three, and each one asks for the best way to cut a range into smaller ranges.
The table you fill has one cell for each range i to j. The table below names the range, the decision that splits it, and what that decision adds to the cell.
| Problem | The range i to j holds | The decision that splits it | What it adds |
|---|---|---|---|
| Fewest cuts into palindromes | letters i to j | where the last piece starts | one cut |
| Cheapest order to split a log file | the points between two cuts | the first cut in the piece | the length of the piece |
| Fewest passes to repaint a billboard row | panels i to j - 1 | a later panel that shares the first pass | nothing, or one pass |
| Merge the trip log shards cheaply | shards i to j | where the first group of k - 1 merges ends | the total size, once the range is one shard |
| Retire the ad slots for the most revenue | the slots between i and j | the slot retired last | three bids multiplied |
In every row the decision gives two smaller ranges that do not touch. That is why a table over ranges works at all, and it is the idea the rest of the lesson uses.
Here is a small case to read before you code. A log file of 10 bytes must be split at the offsets 2, 4 and 7. Each split copies the piece it cuts, and the cost is the length of that piece.
Exercise · Predict the output: The same cuts in two orders. The code splits a file of 10 bytes at the offsets 2, 4 and 7, once in the order 2, 4, 7 and once in the order 4, 7, 2. It adds the length of every piece it cuts. What does it print?
def copy_cost(length, order):
cuts = [0, length]
total = 0
for offset in order:
i = 1
while cuts[i] < offset:
i += 1
total += cuts[i] - cuts[i - 1]
cuts.insert(i, offset)
return total
print(copy_cost(10, [2, 4, 7]), copy_cost(10, [4, 7, 2]))There are 6 orders for 3 cuts, and their costs are 20, 20, 21, 22, 23 and 24. For 100 cuts there are more than 10^157 orders. We cannot try them, so we cut the problem into ranges instead.
The move has two parts.
First, find the one decision in a range that leaves two smaller ranges with no link between them. For the log file, it is the first cut: it copies the whole piece once, and the two pieces it leaves are split on their own. For the ad slots, it is the last slot retired: while it is still there, it keeps the two sides apart.
Second, fill the table by range length. A cell for i to j needs the two cells on its sides, which are both shorter, so a loop over the length always finds them ready.
For a range i to j, let k be the position of the decision that leaves two independent smaller ranges. Then best[i][j] is the best, over every k, of best[i][k] plus best[k][j] plus what the decision itself adds.
For the log file with the offsets 2, 4 and 7, the table gives 20. That is the order 4, 7, 2 from the prediction. The table reaches it without trying any order.
Try each first cut, pay for the whole piece, and add the two smaller pieces. The best total is 20.
Fill order is where this goes wrong first. Both loops below look right, but the cells are not ready when they are read.
Exercise · Find the bug: The cell that is read too early. This fills the table for the log file. It computes each cell from the cells of the two pieces it leaves. It returns a wrong total. Which line is wrong?
def least_split_cost(length, offsets):
points = [0] + sorted(offsets) + [length]
m = len(points)
cost = [[0] * m for _ in range(m)]
for i in range(m):
for j in range(i + 2, m):
best = min(cost[i][k] + cost[k][j] for k in range(i + 1, j))
cost[i][j] = best + points[j] - points[i]
return cost[0][m - 1]The Academy lesson Interval DP fills a table over ranges with one clean split. String DP gives you tables over two indices, and DP from recursion shows why a table can replace a recursion. Here the choice of the decision is the hard part, and four changes follow from it.
The first decision is often the wrong one. For the ad slots, retiring slot k first changes the neighbours of the slots on both sides, so the two sides depend on each other. Retiring it last fixes its neighbours at the range ends.
On the bids 3, 1, 5, 8 the table gives 167. Retiring the smallest bid each time gives 78.
A merge of k items steps by k - 1. Each merge takes k shards and leaves one, so it removes k - 1 shards. A range can become one shard only when its length minus one is a multiple of k - 1. For the shards 3, 2, 4, 1 and k = 3 there is no way, and the answer is -1.
A match lets one decision reach further. In the printer problem a pass over panel i can run on to a later panel of the same colour. The split points are only the panels that match panel i.
One table can feed another. The palindrome problem fills a yes-or-no table over ranges, then a second table over prefixes. The aab case needs 1 cut, and abcde needs 4.
The cost is the cube of the length. For 200 slots the table has about 1,353,400 triples of i, k and j, which is small. For 1,500 or more, you will need a faster tool, and the camp tents later show one.
Retiring the smallest slot first gives 78. Retiring the last slot in each range gives 167.
A shortcut is tempting on the printer problem: count the runs of equal colours. That is right when no colour comes back, and wrong when one does.
Exercise · Break it: Counting the runs. This counts the fewest passes to paint a row of panels by counting the runs of equal colours. Find an input where it gives the wrong answer.
def fewest_passes(panels):
passes = 0
for i in range(len(panels)):
if i == 0 or panels[i] != panels[i - 1]:
passes += 1
return passesSolve them in this order. The first uses a table over ranges to feed a second table. The next three change what the split decision is, and the last one needs you to turn the decision around.
Before you code each problem, write three lines: what the range i to j holds, which decision splits it, and what that decision adds. If you cannot name a decision that leaves two independent sides, try the opposite one: first instead of last, or last instead of first.
Give each problem about 35 minutes. Spend the first ten on the three lines and on a table for a case of three or four items that you fill by hand.
Three checks catch most wrong answers. Fill the table by increasing length. Give the empty and single-item ranges their base values before the loops start. Test the smallest input, such as a row of one panel or a file with one offset.
Checkpoint · Interval DP
Q1/5 A log file of 10 bytes is split at the offsets 2, 4 and 7, and each split copies the piece it cuts. What is the lowest total copying cost?
Answer: B
Cutting at 4 first copies 10 bytes. The piece 0 to 4 then copies 4 and the piece 4 to 10 copies 6, so the total is 20. The order 2, 4, 7 costs 24.
Q2/5 In the ad slot problem, why does the table choose the slot that is retired last in a range?
Answer: B
While the last slot is still in place, nothing on one side can touch the other side. A slot retired first would change the neighbours of the slots around it.
Q3/5 A table over ranges must be filled in a particular order. Which order makes every cell find the cells it needs?
Answer: C
A cell reads the cells of the two shorter ranges on its sides. Filling by increasing length makes both ready. Filling from the top reads cells that are still zero and returned 10 instead of 20 in the lesson.
Q4/5 Five shards are merged three at a time into one shard. A range of shards can end as one shard only when what holds?
Answer: B
Each merge of 3 shards removes 2 shards. A range of length L ends as one shard only when L - 1 is a multiple of 2. For 4 shards and k = 3, the answer is -1.
Q5/5 What is the fewest number of passes for the panel colours 1, 2, 1, and why does counting the runs fail?
Answer: B
A pass paints over what is under it. Paint all three panels with 1, then paint the middle one with 2. The run count says 3.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.