Dynamic programming on a table
- Write four things before any code (what one cell means, the recurrence, the base cases, and an order where every cell's inputs are ready), then check the table against brute force
- Keep two states for each position, one row each, for the longest increasing run when one item may be dropped
- Fill a table over two strings for edit distance and the longest common subsequence, say what each of a cell's three neighbors stands for, and give the O(nm) cost with a measurement
- Return the answer itself by walking back through the table or keeping a parent per cell, and meet a tie rule by filling the table from the other end
- Find the best route through a graph with no cycles in topological order, deeper than the recursion limit, and say what to use when the graph has a cycle
- Add a dimension for a count or a budget, use a bitmask for a small set, keep two rows instead of the table, count instead of optimize, and tell when greedy is enough
The best way down a trail park, the way the coding round asks
An Airbnb software engineer candidate reported a coding round about skiing from the top of a mountain to one of several finish checkpoints, and finding the best-scoring way down (1 report). Minimum Cost to Reach Destination in Time, on an Airbnb LeetCode tag list (1 source), has the shape of the last level: one more number in the state. This lesson's practice problem puts it in a downhill bike park, in three levels:
best_score(stretches, start, exits): the highest total of a route from the trailhead to any exit. Each stretch of trail has a score, and some scores are negative.best_route(stretches, start, exits): the route itself, and when routes tie, the one whose list of junctions comes first.best_score_limited(stretches, start, exits, expert, limit): the best total of a route that rides at mostlimitexpert stretches.
On a park of 13 stretches, from top to the exits gate and lot Returns best_score15, riding past the exit at gate and on to lot best_route["top", "pines", "bowl", "gate", "lot"]best_score_limited, two stretches expert-only, a limit of 113 the same, with a limit of 0 12
Every stretch runs downhill, so the park has no loops, and one test is 50,000 junctions in a row. The lesson builds up to it: the four things to write before any code, two states for each position, a table over two strings, the best route through a graph with no cycles, the answer itself, and a count in the state. 17 steps end with a small task in the editor.
Four things to write down before any code
The coin-change lesson filled a table with one index, the amount. Most dynamic programs in interviews need more than one number to say where you are:
- a position in a list, and how many deletions you've used
- a spot in each of two strings
- a junction on a trail, and how many expert stretches you've ridden to get there
This lesson is about those states with more than one part, and the tables they fill.
grid Start at the green 3 and end at the green 5, moving only right or down.
You start at the top-left cell and move only right or down. You collect the points of every cell you pass. What's the most you can collect by the bottom-right cell?
Moving only right or down, what's the most you can collect by the bottom-right cell?
The loops fill row by row, and each cell reads the cell above and the cell to its left
The code is those four lines of thought, in that order:
import math
def most_points(grid):
rows, cols = len(grid), len(grid[0])
best = [[-math.inf] * cols for _ in range(rows)]
# top to bottom
for r in range(rows):
# left to right
for c in range(cols):
if r == 0 and c == 0:
best[r][c] = grid[0][0]
continue
up = best[r - 1][c] if r > 0 else -math.inf
left = best[r][c - 1] if c > 0 else -math.inf
best[r][c] = grid[r][c] + max(up, left)
return best
grid = [
[3, 1, 4, 1],
[1, 5, 9, 2],
[6, 5, 3, 5],
]
for row in most_points(grid):
print(row)
[3, 4, 8, 9]
[4, 9, 18, 20]
[10, 15, 21, 26]
The corner holds the answer, 26. Here is the order the loops visit the cells, next to the values they write:
fill order best Each cell reads the cell above and the cell to its left, and both are filled before it.
Every cell a cell reads is already filled. That's the fourth item doing its job.
Every cell took one comparison of two neighbors. So the cost is time and memory for a grid of rows and columns.
In the editor, write count_paths(grid): the same four things, counting the paths around walls. It prints the count for a yard with two walls, then for three small grids.
Walk back from the corner to find the path
Now get the path itself back out of the table.
The corner holds 26, and its own points are 5. Which neighbor explains it?
Top-down is the recurrence as a cached function, and the calls find an order by themselves
Why not write the recurrence as a recursive function? Plain recursion asks for the same cells again and again, the overlapping subproblems from the coin-change lesson. On random square grids of digits, one run each:
Plain recursion made 12,869 calls on an 8 by 8 grid. About how many on a 10 by 10?
Swap the two calls in the max, so each call asks left first. In what order do the cells finish?
Any order works if every cell's inputs come first
Every order that works has one thing in common.
The cells and the arrows between them form a graph with no cycles, the kind the topological-sort lesson put in order. A fill order is correct when it is a topological order of that graph: every arrow points forward. Here are three orders:
| Order | Starts with | Gives |
|---|---|---|
| row by row | (0,0) (0,1) (0,2) (0,3) (1,0) | 26 |
| column by column | (0,0) (1,0) (2,0) (0,1) (1,1) | 26 |
| bottom row first | (2,0) (2,1) (2,2) (2,3) (1,0) | wrong: (2,0) reads (1,0), not filled yet |
Row by row and column by column both return 26. The fourth item, the order, is the one people skip. The base cases are the other half of it: they are the cells whose inputs don't exist, and you fill them before anything reads them.
In the editor, write points_to_corner(grid): the most points from each cell to the corner. Its inputs sit below and to the right, so its order runs the other way. It prints the table.
LeetCode's Unique Paths, the number of right-or-down paths across a grid with no walls. Drawn from 0:55 and coded from 8:20. His cells count the paths from each cell to the corner, so a cell adds the cell below it and the cell to its right: the order your points_to_corner used, with a sum where the points took a max.
Deleting one element can join two increasing runs into one
A prep site's question bank lists, for a Netflix data scientist coding round, the longest strictly increasing run you can get by deleting at most one element (1 source). A run here is a stretch of consecutive elements where each is larger than the one before it.
Delete at most one element of 4, 7, 5, 6, 8, 3, 9, 10. What's the longest strictly increasing run you can get?
One number per position forgets whether the deletion is spent
A table can beat trying every deletion, but the first table to try is wrong.
kept The first table to try keeps one number per position: the longest run ending at a[i], with or without a deletion. At the 8 that's 4, the run 4, 5, 6, 8 with the 7 deleted. Delete the 3 too, and that run goes on as 4, 5, 6, 8, 9, 10, so this table says 6.
But that answer deleted two elements. The number at each position forgot whether its run had already spent the deletion. And the deletion is exactly what the next step needs to know.
Two rows: one for nothing deleted, one for at most one deleted
So the state has two parts: the position, and how many deletions the run has used. Write the four things down:
- The cells.
run[0][i]is the longest run that ends ata[i]with nothing deleted.run[1][i]is the longest run that ends ata[i]with at most one element deleted from it. - The recurrence. Both rows grow by one when
a[i - 1] < a[i]. Row 1 has one more way in: deletea[i - 1]and attacha[i]to a run that ends ata[i - 2]. That run must come from row 0, because this step uses the deletion, and it only works ifa[i - 2] < a[i]. - The base cases. A run of one element: every cell starts at 1.
- The order. Left to right. Each cell reads only positions
i - 1andi - 2.
def longest_run_one_out(a):
n = len(a)
if n == 0:
return 0
# run[d][i]: the longest run ending at a[i], at most d deleted
run = [[1] * n, [1] * n]
for i in range(1, n):
if a[i - 1] < a[i]:
run[0][i] = run[0][i - 1] + 1
run[1][i] = run[1][i - 1] + 1
if i >= 2 and a[i - 2] < a[i]:
# delete a[i - 1]
run[1][i] = max(run[1][i], run[0][i - 2] + 1)
return max(run[1])
print(longest_run_one_out([4, 7, 5, 6, 8, 3, 9, 10]))
print(longest_run_one_out([]), longest_run_one_out([5]), longest_run_one_out([2, 2]))
5
0 1 1
The answer is the largest cell in row 1. Here are both rows, and the cell under the 9:
run[0] run[1] The column labels are a[i]. The 4 under the 9 in run[1] comes from run[0] two back: 3 + 1, deleting the 3. run[1] one back gives only 1 + 1 = 2.
It never reads the 4 under the 8, because that run already spent its deletion on the 7.
Check a table you worked out by hand against brute force before you trust it. Your longest_run_brute is that brute force. Here they are on random arrays of 0 to 12 numbers between 0 and 5, full of repeats:
import random
rng = random.Random(1)
for _ in range(2_000):
a = [rng.randint(0, 5) for _ in range(rng.randint(0, 12))]
assert longest_run_one_out(a) == longest_run_brute(a), a
print("matched on 2,000 random arrays")
matched on 2,000 random arrays
On 20,000 of them they matched every time. The edges in the first output are right too: [] gives 0, [5] gives 1, and [2, 2] gives 1, because a strictly increasing run can't hold two equal numbers.
The cost is time and two rows of cells. Each column reads only the two before it, so three columns of two numbers would do.
A sum can also start over, and that rule is Kadane's algorithm
The same two rows work for the largest sum after one deletion, but a sum needs one choice that run lengths didn't. A length always grows when the run goes on. A sum can do better by starting over: if the best sum ending just before x is negative, x alone beats x added to it. So the best sum ending at x is the larger of x and x plus the best sum ending one before. That start-or-extend rule is Kadane's algorithm, and it fills the first row here.
In the editor, finish best_sum_one_out(xs): two rows for the largest sum after one deletion. It prints three sums.
A table over two sequences
Here is a question about two strings at once.
Edit distance is the fewest single-letter edits that turn one string into another. An edit inserts a letter, deletes one, or swaps one letter for another. tails becomes train in 3, as above. Spell checkers rank suggestions by it, and diff and DNA alignment are its relatives.
The state is a pair of positions, one in each string. So the table has a row for each prefix of one string and a column for each prefix of the other.
- The cell.
d[i][j]is the edit distance froma[:i], the firstiletters ofa, tob[:j]. - The recurrence. Look at the last letters,
a[i - 1]andb[j - 1]. If they're equal, keep them:d[i][j] = d[i - 1][j - 1]. If not, the last edit was one of three, and each one is a neighbor of the cell. Sod[i][j] = 1 + min(diagonal, above, left). - The base cases.
d[i][0] = i, deleting every letter, andd[0][j] = j, inserting every letter. - The order. Row by row, left to right. Above, left and the diagonal are all filled first.
Here is what each neighbor stands for:
| The cell read | The last edit it stands for |
|---|---|
d[i-1][j-1], the diagonal | swap a[i-1] for b[j-1], or keep it if they match |
d[i-1][j], above | delete a[i-1] |
d[i][j-1], to the left | insert b[j-1] |
- The diagonal used one letter fewer of both strings, so the last step dealt with both last letters together.
- The cell above used one letter fewer of
a, so the last step dealt witha[i - 1]alone. - The cell to the left used one letter fewer of
b, so the last step dealt withb[j - 1]alone.
In the editor, write edit_distance(a, b) from the four things. It prints the table for tails and train, then three edges.
Fill row by row from a base row and a base column, for O(nm)
Here is the table it fills for tails and train.
for row in edit_distance("tails", "train"):
print(row)
[0, 1, 2, 3, 4, 5]
[1, 0, 1, 2, 3, 4]
[2, 1, 1, 1, 2, 3]
[3, 2, 2, 2, 1, 2]
[4, 3, 3, 3, 2, 2]
[5, 4, 4, 4, 3, 3]
The function returns the whole table. With a's prefixes down the side and b's along the top, it reads like this:
d Row a, column a: the letters match, so the cell copies its diagonal, 1. The corner says tails becomes train in 3 edits.
What it costs. There are cells for strings of lengths and , and each one is a comparison and a min of three. That's time and memory. Measured on random strings of the letters A, C, G and T, best of 3 runs:
Double both string lengths. About how much longer does the table take?
The longest common subsequence fills the same table with other rules
The same table answers a second question about two strings.
A subsequence keeps some letters in their order and drops the rest. What's the longest one that tails and train share?
A downhill park is a graph with no cycles
Now the practice problem's bike park. There are one-way stretches of trail between junctions, each worth a score that can be negative. There is a trailhead at the top, and several exits where a ride may end. Here is a small park:
PARK = [
("top", "birch", 2),
("top", "ash", 3),
("ash", "cliff", 4),
("birch", "cliff", 4),
("birch", "dell", 6),
("cliff", "falls", 5),
("cliff", "end", 1),
("dell", "end", 2),
]
EXITS = ["end", "falls"]
junctions = {j for upper, lower, _ in PARK for j in (upper, lower)}
print(len(PARK), "stretches between", len(junctions), "junctions")
8 stretches between 7 junctions
What's the best total of a route from top to an exit?
The four things for the best total from the trailhead
Write the four things down for the park first.
- The cell.
best[j]is the highest total of a route fromtopto junctionj, or minus infinity when no route reachesj. - The recurrence.
best[lower]is the max, over the stretches intolower, ofbest[upper] + score. - The base case.
best[top] = 0, and every other junction starts at minus infinity, not 0. - The order. A topological order. Every stretch into a junction comes from a junction earlier in the order, so its
bestis final by the time it's read.
Minus infinity is how the table says no route. Adding a score to it leaves it at minus infinity, so it never wins a max. An exit still at minus infinity at the end can't be reached. If every exit is, the answer is None.
Top-down reads like the recurrence, and on a long chain it can pass Python's recursion limit
Top-down comes first, because it's the recurrence almost word for word. Ask from the other end: the best total from a junction to an exit. Let functools.cache remember each answer.
import math
from collections import defaultdict
from functools import cache
def best_score_top_down(stretches, start, exits):
below = defaultdict(list)
for upper, lower, score in stretches:
below[upper].append((lower, score))
exits = set(exits)
@cache
# the best total from j to an exit
def down(j):
best = 0 if j in exits else -math.inf
for lower, score in below[j]:
best = max(best, score + down(lower))
return best
best = down(start)
return None if best == -math.inf else best
print(best_score_top_down(PARK, "top", EXITS))
12
An exit starts at 0, the ride that stops there. It still looks below itself, because a route may ride past an exit. On PARK the best is 12: top, ash, cliff, falls. The recursion finds the order for you, since down(j) can't return until every junction below it has.
It also inherits the recursion limit. Take a chain of junctions, each with one stretch to the next:
998 calls open at once, the most that works. One more junction raises RecursionError.
Run from a script, the function worked on a chain of 998 junctions and raised RecursionError: maximum recursion depth exceeded on 999. Python's default limit is 1,000 frames, and the script itself uses a few. A park is something people build, and a long chain of junctions is fair input. Raising the limit is a gamble: the Python docs warn that a limit set too high can lead to a crash.
Bottom-up in topological order has no depth at all
Kahn's algorithm from the topological-sort lesson gives the order. Read a stretch from upper down to lower as the arrow from a prerequisite to the task that needs it. With park_order(stretches, start) returning below and that order, the pass from the start is a few lines:
def best_from_start(stretches, start, exits):
below, order = park_order(stretches, start)
# -inf: no route from start reaches it
best = dict.fromkeys(order, -math.inf)
best[start] = 0
# every stretch into j comes from earlier in the order
for j in order:
for lower, score in below[j]:
best[lower] = max(best[lower], best[j] + score)
reached = [best[e] for e in exits if best.get(e, -math.inf) != -math.inf]
return max(reached) if reached else None
print(park_order(PARK, "top")[1])
print(best_from_start(PARK, "top", EXITS))
['top', 'birch', 'ash', 'dell', 'cliff', 'falls', 'end']
12
In the editor, write park_order(stretches, start) with Kahn's algorithm. It prints the park's order, then two edges.
The table fills one junction at a time, in Kahn's order
Here is the table, one junction at a time in that order. Each row shows the totals offered by the stretches into it:
cliff hears from birch, 2 + 4, and from ash, 3 + 4. What does best[cliff] keep?
Start every junction at 0 instead of minus infinity. Then ask for the best route from dell, with falls as the only exit. What comes back?
A cycle breaks the order, the recursion, and sometimes the idea of a best route
Add a lift that carries riders from falls back to top, ("falls", "top", 1), and the park has a cycle:
Three things go wrong.
- No order exists.
best[top]now depends onbest[falls], which depends onbest[top]. Kahn's order comes out short, here empty, sincetopwaits onfalls. Andbest_from_startquietly returnsNone. - The recursion never bottoms out.
down("top")asksdown("birch"), which works down throughclifftodown("falls"). That asksdown("top")again before its first call has returned, so nothing is in the cache yet. It raisesRecursionError. - There may be no best at all. The loop adds 13 points every lap, so a route that may repeat junctions has no highest score. Forbid repeats and you get the longest simple path, which in general graphs is NP-complete. The booksite's chapter on intractability lists it among its sample of NP-complete problems.
With a cycle, pick the tool by what you optimize
A cycle doesn't end the question. It changes the tool.
- The cheapest route, with costs that are never negative: Dijkstra's algorithm.
- The cheapest route with some negative costs: Bellman-Ford, , which also detects a negative cycle. The booksite names the two easy cases: all weights nonnegative, or no cycles. Bellman-Ford covers the rest, as long as no cycle is negative.
- The best simple path on a small graph: put a bitmask of the junctions visited into the state, for . That's fine up to about 20 junctions. The follow-ups show the bitmask.
- Something in the state that only grows, like minutes or steps. Then a move can never return to the same state, and the cyclic graph becomes a DAG of states. The worked example does exactly that.
Walk back through the table, or keep a parent for each cell
A table holds scores. When the question asks for the edits, the subsequence or the route, there are two ways to get it.
Walk back through the table. Start at the cell that holds the answer, and ask which neighbor explains its value. The booksite describes it for the longest common subsequence: retrace the steps of the algorithm backward, and rediscover the path of choices. For edit distance:
- a cell equal to its diagonal, with matching letters, was a keep
- a cell one more than its diagonal was a swap
- one more than the cell above was a delete
- one more than the cell to the left was an insert
def edit_script(a, b):
d = edit_distance(a, b)
i, j, ops = len(a), len(b), []
while i > 0 or j > 0:
if i > 0 and j > 0 and a[i - 1] == b[j - 1] and d[i][j] == d[i - 1][j - 1]:
ops.append(f"keep {a[i - 1]}")
i, j = i - 1, j - 1
elif i > 0 and j > 0 and d[i][j] == d[i - 1][j - 1] + 1:
ops.append(f"swap {a[i - 1]} for {b[j - 1]}")
i, j = i - 1, j - 1
elif i > 0 and d[i][j] == d[i - 1][j] + 1:
ops.append(f"delete {a[i - 1]}")
i -= 1
else:
ops.append(f"insert {b[j - 1]}")
j -= 1
return ops[::-1]
print(edit_script("tails", "train"))
The walk back starts at the corner of the tails and train table. Which edit is the last one in the script?
When two answers tie, decide which one you return, and say it
tails to train has two scripts of 3 edits. Checked in the order above, diagonal first, the walk ends with delete l, swap s for n. Check the cell above first, and it ends with swap l for n, delete s. Both are right. When the answer isn't unique, decide which one you return and say so, or ask. A test that compares lists will pin down one.
A tie rule that reads the route from the front needs the table filled from the other end
On a graph, a tie rule can decide the direction of the whole table. Add one stretch to the park, ("dell", "falls", 4). Now two routes score 12. Say the rule is the one the practice problem uses: return the route whose list of junctions comes first in Python's list order.
Two routes score 12: top, ash, cliff, falls and top, birch, dell, falls. Which list comes first in Python's order?
One total per junction can keep the wrong total when a limit applies
Mark two stretches of the park as expert-only, top to ash and cliff to falls. Allow a route at most one of them. The best route, top, ash, cliff, falls, rides both, so it's out.
With at most one expert stretch, what's the best total now?
Add the count to the cell, and take the best over every count up to the limit
So write the four things again, with the count in the cell.
- The cell.
best[j][u]is the highest total of a route from the start tojthat rode exactlyuexpert stretches. - The recurrence. A stretch from
jtolowerworthscoremoves a route frombest[j][u]tobest[lower][u + 1]if it's expert, and tobest[lower][u]if not, as long as the count stays within the limit. - The base case.
best[start][0] = 0, and every other cell starts at minus infinity. - The order. Junctions in topological order, all of a junction's counts at once. Every stretch leads to a junction later in the order, so nothing in a later column feeds an earlier one.
The answer is the best cell at any exit, in any row up to the limit: at most the limit, not exactly. With a limit of 1:
best · is minus infinity: no route. An expert stretch moves a total down one row: top's 0 to ash's 3, and cliff's 6 to falls's 11.
cliff keeps both totals, 6 with the expert stretch unspent and 7 with it spent, and falls gets its 11 from the 6. With a limit of 0 the answer is 10, with 1 it's 11, and with 2 it's 12, the unlimited best.
A limit of k multiplies the work by k + 1, and k never needs to pass E
The table has cells for junctions and a limit of . Every stretch is tried once per count. So the cost is time and memory.
A route can't ride more expert stretches than the park has, so never needs to pass , and this stays polynomial. A budget is different. One row per minute or per dollar is the coin-change lesson's pseudo-polynomial warning: a budget of a billion minutes is a table of a billion rows per junction.
In the editor, fill the inner loop of best_limited(below, order, start, exits, limit). It prints the best total for limits of 0, 1 and 2.
A worked example: the cheapest trip that arrives in time
Minimum Cost to Reach Destination in Time is on an Airbnb LeetCode tag list (1 source). In our setting, a courier crosses a city of districts numbered from 0. Roads run both ways and take whole minutes, at least one each. Every district charges a fee each time the courier is in it, the first and the last included. Find the cheapest trip from district 0 to the last district that takes at most limit minutes, or None.
The trip runs from district 0 to district 4.
The limit here is 12 minutes.
Within 12 minutes, which trip is the cheapest?
Put the minute in the state, and the states have no cycles
3. The insight. The cheapest arrival at a district isn't one number, because it depends on when you arrive. Put the minute in the state. The cell cost[t][v] is the cheapest fee total for standing in district v at exactly minute t.
On the map, a road leads back from 1 to 0. As states, every road leads to a later minute:
Every road moves from minute t to a later minute, so no state can lead back to itself. The road map has cycles, and the states don't. Filling the table by minute, from 0 up to the limit, is a topological order of the states.
import math
def cheapest_in_time(n, roads, fees, limit):
# cost[t][v]: cheapest fees to be in v at minute t
cost = [[math.inf] * n for _ in range(limit + 1)]
cost[0][0] = fees[0]
# minutes only go up: a topological order
for t in range(limit + 1):
for a, b, minutes in roads:
if t + minutes <= limit:
# both ways
for u, v in ((a, b), (b, a)):
if cost[t][u] + fees[v] < cost[t + minutes][v]:
cost[t + minutes][v] = cost[t][u] + fees[v]
best = min(cost[t][n - 1] for t in range(limit + 1))
return None if best == math.inf else best
# (district, district, minutes)
ROADS = [(0, 2, 10), (0, 1, 2), (1, 2, 2), (2, 4, 6), (0, 3, 3), (3, 4, 3)]
FEES = [1, 5, 1, 12, 1]
print(cheapest_in_time(5, ROADS, FEES, 12))
print([cheapest_in_time(5, ROADS, FEES, limit) for limit in (5, 6, 10, 16)])
With a limit of 5 minutes instead of 12, what does cheapest_in_time return?
Trace the table, test it against brute force, and give the cost
4. Trace it. The rows for each minute, with blanks for unreachable:
District 2 is reached for 7 at minute 4, and for 2 at minute 10 by the direct road. Which one leads to the answer?
Less memory? Often two rows will do, and the walk back is the price
Each row of the edit distance table reads only the row above it, so keep two rows and swap them:
def edit_distance_two_rows(a, b):
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1])
prev = cur
return prev[-1]
print(edit_distance_two_rows("tails", "train"))
3
The same answer from two rows. Here is what the function holds while it fills the last row:
full two rows The walk back needs the rows that are gone: it runs from the corner up to row "".
At 2,000 letters each, the full table peaked at 118 MiB. About how much do two rows take?
A budget instead of a count? One row per value of the budget
Minutes, money or weight work like the expert count: one row per value of the budget. That's what the worked example did with minutes.
When the budget is huge but only a few values are reachable, key a dict by the values that occur, instead of a list over all of them. Or swap what's stored and what's indexed: for each score, store the fewest minutes that reach it.
A small set? Put it in a bitmask
Smallest Sufficient Team is on an Airbnb LeetCode tag list, tagged Bitmask (1 source). The task is the fewest people who together have every required skill. The state is the set of skills covered so far. With 16 skills or fewer, a set fits in an integer whose bit k says whether skill k is covered.
The state is the set of skills covered so far. With 16 skills, how many states can there be?
How many routes share the best score? Keep a count next to each total
A stretch that beats a junction's total replaces its count. One that ties it adds to it:
if best[j] + score > best[lower]:
# a better total: start the count over
best[lower], ways[lower] = best[j] + score, ways[j]
elif best[j] + score == best[lower]:
# a tie: add the routes
ways[lower] += ways[j]
Forget scores and count every route from top to an exit in PARK. How many are there?
When is greedy enough? When the best-looking step can never rule out the best answer
You can show greedy is safe by swapping any other choice for the greedy one, and losing nothing. Text Justification is on Airbnb LeetCode tag lists from two different compilations (3 sources) and in a prep guide to Anthropic's interviews (1 source). As asked, it is greedy: each line takes as many words as fit, then the spaces are spread.
Change the goal to the fewest squared spaces at the ends of lines, with the last line free. Here is then go up a red trail at width 10:
Greedy fills each line as full as it can and pays 25. What does a table over the line breaks pay?
Word Break is the same four things on a one-dimensional table
Word Break is on Netflix's tag list (1 source): can a string be split into dictionary words?
- The cell: whether the first
iletters can be split. - The recurrence: some earlier split point
jworks, ands[j:i]is a word. - The base: the empty prefix can be split.
- The order: left to right.
With a longest word of letters, only the last split points can matter. So it's checks, each a slice of at most letters and a set lookup.
In the editor, write can_break(s, words) on a one-dimensional table. It cuts two strings of park words.
The tests you'd write: brute force on small inputs first, then the edges
Brute force on small random inputs comes first. The run with one deletion, the trip in time and the team were each checked against it above. The practice problem's worked solution matched trying every route on 3,000 random small parks.
Then the edges:
- an empty input, and one element
- a tie
- something unreachable
- scores below zero
- a limit of 0
- a chain longer than 1,000, listed in both directions, for the recursion limit
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.What makes an order of filling a dynamic programming table correct?
2.For the longest increasing run with one deletion, why does the table need a row for nothing deleted and a row for at most one deleted?
3.In the edit distance table, what does moving from
d[i - 1][j]tod[i][j]stand for?4.Several routes share the best score, and you must return the one whose list of junctions comes first. A forward pass that keeps a parent for each junction returns a best route that isn't that one. What fixes it?
5.A lift is added that carries riders from an exit back up to the trailhead, and every lap of the loop is worth points. What happens to the best route?
6.A route may ride at most k expert stretches. Why does the table need a cell for every junction and every count up to k?
Practice
Sources (8)
- 2.3 Recursion: dynamic programming · Introduction to Programming in Java (Sedgewick and Wayne), booksite · May 24, 2020
“By solving each subproblem only once (instead of over and over), this technique avoids a potential exponential blow-up in the running time.”
- 2.3 Recursion: longest common subsequence · Introduction to Programming in Java (Sedgewick and Wayne), booksite · May 24, 2020
“The key idea is to retrace the steps of the dynamic programming algorithm backward, rediscovering the path of choices”
- 2.3 Recursion: dynamic programming, memory · Introduction to Programming in Java (Sedgewick and Wayne), booksite · May 24, 2020
“for the longest common subsequence problem, it is easy to avoid the 2D array if you only need the length of LCS”
- 4.4 Shortest Paths: edge-weighted DAGs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 10, 2025
“By relaxing vertices in topological order, we can solve the single-source shortest-paths and longest-paths problems for edge-weighted DAGs in time proportional to E + V.”
- 4.4 Shortest Paths: longest paths in edge-weighted DAGs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 10, 2025
“We can solve the single-source longest paths problems in edge-weighted DAGs by initializing the distTo[] values to negative infinity and switching the sense of the inequality in relax().”
- 4.4 Shortest Paths: general edge-weighted digraphs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 10, 2025
“We can solve shortest path problems if (i) all weights are nonnegative or (ii) there are no cycles.”
- 6.6 Intractability: some NP-complete problems · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Aug 26, 2016
“Longest path. Given a set of nodes and pairwise distances between nodes, does there exists a simple path of length at least L connecting some pair of nodes?”
- sys.setrecursionlimit · Python 3.12 documentation · Oct 26, 2026
“This should be done with care, because a too-high limit can lead to a crash.”