Library/Coding patterns that get asked/Graphs, trees and tables

Dynamic programming on a table

100 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • 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:

  1. 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.
  2. best_route(stretches, start, exits): the route itself, and when routes tie, the one whose list of junctions comes first.
  3. best_score_limited(stretches, start, exits, expert, limit): the best total of a route that rides at most limit expert stretches.
On a park of 13 stretches, from top to the exits gate and lotReturns
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 012

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.

Part 1 of 7about 21 min
Four things

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.

Collect points from the top-left to the bottom-right
grid
314115926535

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?

Predict

Moving only right or down, what's the most you can collect by the bottom-right cell?

Pick an answer above to see the rest

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:

The order the loops fill it, and the values they write
fill order
123456789101112
best
348949182010152126

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 O(RC)O(RC) time and memory for a grid of RR rows and CC 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.

Predict

The corner holds 26, and its own points are 5. Which neighbor explains it?

Pick an answer above to see the rest

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:

Predict

Plain recursion made 12,869 calls on an 8 by 8 grid. About how many on a 10 by 10?

Pick an answer above to see the rest
Predict

Swap the two calls in the max, so each call asks left first. In what order do the cells finish?

Pick an answer above to see the rest

Any order works if every cell's inputs come first

Every order that works has one thing in common.

Each arrow runs from a cell to a cell that reads it
(0,0)(0,1)(0,2)(0,3)(1,0)(1,1)(1,2)(1,3)(2,0)(2,1)(2,2)(2,3)

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:

OrderStarts withGives
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.

Watch · 10 min

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.

Unique Paths - Dynamic Programming - Leetcode 62 · NeetCode · Jan 2021YouTube
Part 1 done
Part 2 of 7about 11 min
Two states

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.

Predict

Delete at most one element of 4, 7, 5, 6, 8, 3, 9, 10. What's the longest strictly increasing run you can get?

Pick an answer above to see the rest

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.

A run of 6, with two deletions
kept
4·568·910

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:

  1. The cells. run[0][i] is the longest run that ends at a[i] with nothing deleted. run[1][i] is the longest run that ends at a[i] with at most one element deleted from it.
  2. The recurrence. Both rows grow by one when a[i - 1] < a[i]. Row 1 has one more way in: delete a[i - 1] and attach a[i] to a run that ends at a[i - 2]. That run must come from row 0, because this step uses the deletion, and it only works if a[i - 2] < a[i].
  3. The base cases. A run of one element: every cell starts at 1.
  4. The order. Left to right. Each cell reads only positions i - 1 and i - 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:

Both rows, and the cell under the 9
run[0]
47568391012123123
run[1]
47568391012234145

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 O(n)O(n) time and two rows of nn 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.

Part 2 done
Part 3 of 7about 12 min
Two sequences

A table over two sequences

Here is a question about two strings at once.

tails becomes train in 3 editsInteractive
tails.

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.

  1. The cell. d[i][j] is the edit distance from a[:i], the first i letters of a, to b[:j].
  2. The recurrence. Look at the last letters, a[i - 1] and b[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. So d[i][j] = 1 + min(diagonal, above, left).
  3. The base cases. d[i][0] = i, deleting every letter, and d[0][j] = j, inserting every letter.
  4. 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 readThe last edit it stands for
d[i-1][j-1], the diagonalswap a[i-1] for b[j-1], or keep it if they match
d[i-1][j], abovedelete a[i-1]
d[i][j-1], to the leftinsert 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 with a[i - 1] alone.
  • The cell to the left used one letter fewer of b, so the last step dealt with b[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:

The edit distance table for tails and train
d
""train""012345t101234a211123i322212l433322s544433

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 (n+1)(m+1)(n + 1)(m + 1) cells for strings of lengths nn and mm, and each one is a comparison and a min of three. That's O(nm)O(nm) time and memory. Measured on random strings of the letters A, C, G and T, best of 3 runs:

Predict

Double both string lengths. About how much longer does the table take?

Pick an answer above to see the rest

The longest common subsequence fills the same table with other rules

The same table answers a second question about two strings.

Predict

A subsequence keeps some letters in their order and drops the rest. What's the longest one that tails and train share?

Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 15 min
A park with no cycles

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
The park, with each stretch's score
23644215topbirchashdellcliffendexitfallsexit
Predict

What's the best total of a route from top to an exit?

Pick an answer above to see the rest

The four things for the best total from the trailhead

Write the four things down for the park first.

  1. The cell. best[j] is the highest total of a route from top to junction j, or minus infinity when no route reaches j.
  2. The recurrence. best[lower] is the max, over the stretches into lower, of best[upper] + score.
  3. The base case. best[top] = 0, and every other junction starts at minus infinity, not 0.
  4. The order. A topological order. Every stretch into a junction comes from a junction earlier in the order, so its best is 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:

A chain of 998 junctions, top-down
down(j0)
down(j1)
down(j2)
...
down(j997)the exit, the first call to return

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:

Predict

cliff hears from birch, 2 + 4, and from ash, 3 + 4. What does best[cliff] keep?

Pick an answer above to see the rest
Predict

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?

Pick an answer above to see the rest

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:

One lap: 3 + 4 + 5 + 1 = 13 points, and the lap can repeat
345the lift, 1topashclifffalls

Three things go wrong.

  • No order exists. best[top] now depends on best[falls], which depends on best[top]. Kahn's order comes out short, here empty, since top waits on falls. And best_from_start quietly returns None.
  • The recursion never bottoms out. down("top") asks down("birch"), which works down through cliff to down("falls"). That asks down("top") again before its first call has returned, so nothing is in the cache yet. It raises RecursionError.
  • 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, O(VE)O(VE), 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 O(2VV2)O(2^V V^2). 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.
Part 4 done
Part 5 of 7about 16 min
The answer and a limit

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"))
Predict

The walk back starts at the corner of the tails and train table. Which edit is the last one in the script?

Pick one to see what it prints.
Pick an answer above to see the rest

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.

Predict

Two routes score 12: top, ash, cliff, falls and top, birch, dell, falls. Which list comes first in Python's order?

Pick an answer above to see the rest

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.

Predict

With at most one expert stretch, what's the best total now?

Pick an answer above to see the rest

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.

  1. The cell. best[j][u] is the highest total of a route from the start to j that rode exactly u expert stretches.
  2. The recurrence. A stretch from j to lower worth score moves a route from best[j][u] to best[lower][u + 1] if it's expert, and to best[lower][u] if not, as long as the count stays within the limit.
  3. The base case. best[start][0] = 0, and every other cell starts at minus infinity.
  4. 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[j][u] with a limit of 1
best
topbirchashdellclifffallsendu = 002·86·10u = 1··3·7118

· 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 V(k+1)V(k + 1) cells for VV junctions and a limit of kk. Every stretch is tried once per count. So the cost is O((V+E)(k+1))O((V + E)(k + 1)) time and O(V(k+1))O(V(k + 1)) memory.

A route can't ride more expert stretches than the park has, so kk never needs to pass EE, 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.

Part 5 done
Part 6 of 7about 6 min
The worked example

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 city, with minutes on each road, both ways
22103631, fee 50, fee 12, fee 13, fee 124, fee 1

The trip runs from district 0 to district 4.

The limit here is 12 minutes.

Predict

Within 12 minutes, which trip is the cheapest?

Pick an answer above to see the rest

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:

The same two districts, as statesInteractive
(0, minute 0).

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)])
Predict

With a limit of 5 minutes instead of 12, what does cheapest_in_time return?

Pick one to see what it prints.
Pick an answer above to see the rest

Trace the table, test it against brute force, and give the cost

4. Trace it. The rows for each minute, with blanks for unreachable:

Predict

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?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 19 min
Follow-ups

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:

The full table, and the two rows left while row s is filled
full
""train""012345t101234a211123i322212l433322s544433
two rows
""trainl433322s544433

The walk back needs the rows that are gone: it runs from the corner up to row "".

Predict

At 2,000 letters each, the full table peaked at 118 MiB. About how much do two rows take?

Pick an answer above to see the rest

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.

Predict

The state is the set of skills covered so far. With 16 skills, how many states can there be?

Pick an answer above to see the rest

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]
Predict

Forget scores and count every route from top to an exit in PARK. How many are there?

Pick an answer above to see the rest

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:

Predict

Greedy fills each line as full as it can and pays 25. What does a table over the line breaks pay?

Pick an answer above to see the rest

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?

  1. The cell: whether the first i letters can be split.
  2. The recurrence: some earlier split point j works, and s[j:i] is a word.
  3. The base: the empty prefix can be split.
  4. The order: left to right.

With a longest word of LL letters, only the last LL split points can matter. So it's O(nL)O(nL) checks, each a slice of at most LL 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.

Check yourself
6 questions
  1. 1.What makes an order of filling a dynamic programming table correct?

  2. 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. 3.In the edit distance table, what does moving from d[i - 1][j] to d[i][j] stand for?

  4. 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. 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. 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)
  1. 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. 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”
  3. 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.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.”
  5. 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().”
  6. 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.”
  7. 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?”
  8. 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.”