Dynamic Programming Questions
Solving problems with overlapping subproblems and optimal substructure by memoization (top-down) and tabulation (bottom-up). Covers recognizing DP-amenable problems, defining state, transition and base cases, 1D and 2D sequence and grid formulations (knapsack and its variants, coin change, LIS, LCS, edit distance, sequence alignment, regular-expression and wildcard matching, counting-ways problems), interval DP (matrix chain, palindrome partitioning), space optimization with rolling arrays, solution reconstruction, longest paths in a DAG, game and expected-value DP, bitmask and tree DP, speeding up a DP (monotone queue, convex hull trick, divide-and-conquer optimization, bitsets, meet in the middle), and judging greedy versus DP. Ground covered elsewhere: probabilistic model inference, production caching and debugging practice, and general graph shortest-path algorithms.
A robot starts at the top-left of an m by n grid and can only move right or down. Count the distinct paths to the bottom-right in O(mn) time, then reduce the extra space to O(n). Is there a closed-form answer, and why might you still prefer the DP?
Sample Answer
The idea
A robot that can only move right or down reaches any cell from the cell above it or the cell to its left, and from nowhere else. Every path to a cell therefore ends with one of those two moves, so the number of paths to a cell is the sum of the numbers of paths to those two neighbours. That sum, computed for all cells in order, is dynamic programming (DP): solving each small subproblem once and reusing it.
The five things to state
- What one cell means.
table[i][j]is the number of right/down paths from the top-left cell (0, 0) to cell (i, j). - The transition.
table[i][j] = table[i-1][j] + table[i][j-1]: paths arriving from above plus paths arriving from the left. The two groups cannot overlap because the last move differs. - Base cases. The entire top row and left column are 1: there is only one way to get to a cell on the edge (all rights, or all downs), and
table[0][0] = 1for the empty path. - Fill order. Row by row, left to right, so that both neighbours are filled before the cell that reads them.
- Where the answer is.
table[m-1][n-1], the bottom-right cell.
Brute force first
The recursion go(r, c) returns 1 on the last row or last column (from there only one path remains) and otherwise adds go(r+1, c) and go(r, c+1). Counting every call, the root included, gives 55 calls for a 3 x 7 grid, 1,847 for 7 x 7 and 97,239 for 10 x 10. Each equals 2 x paths - 1 (28, 924 and 48,620 paths), because the recursion bottoms out one call per path and every branch point adds one more. With a cache keyed on (r, c) the calls are 25, 73 and 163, which is 2 x (m-1)(n-1) + 1: each interior cell is computed once and the rest are hits.
The code
import itertools
import math
import random
def paths_brute(m, n):
calls = [0]
def go(r, c):
calls[0] += 1
if r == m - 1 or c == n - 1:
return 1
return go(r + 1, c) + go(r, c + 1)
return go(0, 0), calls[0]
def paths_memo(m, n):
memo, calls = {}, [0]
def go(r, c):
calls[0] += 1
if r == m - 1 or c == n - 1:
return 1
if (r, c) not in memo:
memo[(r, c)] = go(r + 1, c) + go(r, c + 1)
return memo[(r, c)]
return go(0, 0), calls[0]
def paths_table(m, n):
"""table[i][j] = number of right/down paths from (0, 0) to (i, j)."""
table = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
table[i][j] = table[i - 1][j] + table[i][j - 1]
return table
def paths_one_row(m, n):
row = [1] * n # row 0
for _ in range(1, m):
for j in range(1, n): # left to right: row[j-1] is already this row's value
row[j] += row[j - 1]
return row[-1]
def paths_one_row_reversed(m, n):
row = [1] * n
for _ in range(1, m):
for j in range(n - 1, 0, -1): # right to left: row[j-1] is still last row's value
row[j] += row[j - 1]
return row[-1]
def paths_with_blocks(m, n, blocked):
row = [0] * n
row[0] = 0 if (0, 0) in blocked else 1
for i in range(m):
for j in range(n):
if (i, j) in blocked:
row[j] = 0
elif j > 0:
row[j] += row[j - 1]
return row[-1]
def paths_with_blocks_brute(m, n, blocked):
def go(r, c):
if r >= m or c >= n or (r, c) in blocked:
return 0
if (r, c) == (m - 1, n - 1):
return 1
return go(r + 1, c) + go(r, c + 1)
return go(0, 0)
for row in paths_table(3, 4):
print(row)
print("answer:", paths_table(3, 4)[-1][-1], "| closed form C(5, 2):", math.comb(3 + 4 - 2, 3 - 1))
print(" m n paths recursion_calls memo_calls")
for m, n in ((1, 1), (1, 5), (2, 2), (3, 7), (7, 7), (10, 10)):
value, c1 = paths_brute(m, n)
_, c2 = paths_memo(m, n)
print(f"{m:2d} {n:2d} {value:6d} {c1:16d} {c2:11d}")
moves = 3 + 4 - 2
print("3 x 4 grid: down moves sit at these positions among", moves, "moves:", list(itertools.combinations(range(moves), 2)))
print("one row, left to right:", paths_one_row(3, 7), "| right to left:", paths_one_row_reversed(3, 7))
print("18 x 18 grid:", paths_one_row(18, 18), "= C(34, 17) =", math.comb(34, 17))
print("20! fits in signed 64 bits:", math.factorial(20) <= 2**63 - 1, "| 21! fits:", math.factorial(21) <= 2**63 - 1)
print("17 x 17:", paths_one_row(17, 17), "fits in signed 32 bits:", paths_one_row(17, 17) <= 2**31 - 1, "| 18 x 18 fits:", paths_one_row(18, 18) <= 2**31 - 1)
MOD = 10**9 + 7
fact = [1]
for k in range(1, 35):
fact.append(fact[-1] * k % MOD)
via_inverse = fact[34] * pow(fact[17] * fact[17] % MOD, -1, MOD) % MOD
print("C(34, 17) mod 1e9+7 from factorials and an inverse:", via_inverse, "| direct:", math.comb(34, 17) % MOD)
print("100 x 100 grid has", len(str(paths_one_row(100, 100))), "digits")
print("3 x 3 with the centre blocked:", paths_with_blocks(3, 3, {(1, 1)}), "| start blocked:", paths_with_blocks(3, 3, {(0, 0)}))
random.seed(6)
for _ in range(400):
m, n = random.randint(1, 8), random.randint(1, 8)
expected = math.comb(m + n - 2, m - 1)
assert paths_brute(m, n)[0] == paths_memo(m, n)[0] == paths_table(m, n)[-1][-1] == paths_one_row(m, n) == expected
blocked = {(random.randrange(m), random.randrange(n)) for _ in range(random.randint(0, 4))}
assert paths_with_blocks(m, n, blocked) == paths_with_blocks_brute(m, n, blocked)
print("400 random grids: DP, closed form and brute force agree; blocked-cell variant matches brute force")
Output:
[1, 1, 1, 1]
[1, 2, 3, 4]
[1, 3, 6, 10]
answer: 10 | closed form C(5, 2): 10
m n paths recursion_calls memo_calls
1 1 1 1 1
1 5 1 1 1
2 2 2 3 3
3 7 28 55 25
7 7 924 1847 73
10 10 48620 97239 163
3 x 4 grid: down moves sit at these positions among 5 moves: [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
one row, left to right: 28 | right to left: 4
18 x 18 grid: 2333606220 = C(34, 17) = 2333606220
20! fits in signed 64 bits: True | 21! fits: False
17 x 17: 601080390 fits in signed 32 bits: True | 18 x 18 fits: False
C(34, 17) mod 1e9+7 from factorials and an inverse: 333606206 | direct: 333606206
100 x 100 grid has 59 digits
3 x 3 with the centre blocked: 2 | start blocked: 0
400 random grids: DP, closed form and brute force agree; blocked-cell variant matches brute force
Reading the output
- The filled table for a 3 x 4 grid shows the first row and first column as 1s and the answer 10 in the bottom-right corner.
- One row. Row i depends only on row i-1 and on the cell to its left, so one row of n cells is enough:
row[j] += row[j-1]. The sweep must go left to right. At the momentrow[j]is updated,row[j]still holds the value from the row above (the "from above" count) androw[j-1]has already been updated to hold the current row's value (the "from the left" count). Sweeping right to left reads the stale value ofrow[j-1]from the row above instead, and the 3 x 7 grid prints 4 instead of 28. - The closed form agrees: the 3 x 4 grid gives C(5, 2) = 10, and 18 x 18 gives 2,333,606,220 = C(34, 17).
- The check compares the plain recursion, the memoized recursion, the table, the one-row version and the closed form on 400 seeded grids, and compares the blocked-cell variant with an independent brute force.
Closed form and why prefer the DP anyway
Any path from the top-left to the bottom-right makes m-1 moves down and n-1 moves right, in some order. Choosing which of the m+n-2 moves are the downward ones gives C(m+n-2, m-1) paths, computed by math.comb with no table. C(N, k), read "N choose k", is the number of ways to pick k items out of N when the order of picking does not matter. Here a path is a string of moves such as down, right, right, down, right, and it is fixed completely by the positions of its downs; so the number of paths is the number of ways to pick those positions. For the 3 x 4 grid there are 5 moves, 2 of them down, and the program prints the 10 possible position pairs, matching C(5, 2) = 10 and the table's corner. Still, the DP is usually the answer an interviewer wants, for these reasons:
- Obstacles. Blocked cells break the counting argument but not the DP: set the blocked cell to 0 and the same sum applies. The variant in the code gives 2 paths for a 3 x 3 grid with the centre blocked and 0 if the start is blocked, and matches brute force in the random check.
- Other constraints, such as costs, or a rule that forbids a move, extend the DP in one line and have no closed form.
- Overflow. In a fixed-width language (one where integers have a fixed size, such as 32 or 64 bits, and overflow when a result is too large) the factorial route breaks first: 20! fits in a signed 64-bit integer (a whole number with a sign, at most 2^63 - 1, about 9.2 x 10^18) and 21! does not (printed above), so
n!cannot be computed directly for the larger grids, whereas the DP only adds numbers no larger than the answer. The DP result itself exceeds a signed 32-bit integer (at most 2^31 - 1 = 2,147,483,647) at 18 x 18 (17 x 17 fits). A 100 x 100 grid has 59 digits, so a modulus (such as 10^9+7) must be applied at each addition in a fixed-width language. For a huge grid with a modulus, the closed form with precomputed factorials and modular inverses is the faster tool, which is a good thing to say out loud. The idea: C(N, k) = N! / (k! (N-k)!), and under a prime modulus you cannot divide, but you can multiply by the modular inverse of the denominator (the number x with x times the denominator leaving remainder 1; Python'spow(d, -1, MOD)finds it). The factorials up to N are computed once, so each query costs a few multiplications; the program prints C(34, 17) this way next to the direct value. Interviews typically stop at the DP and themath.combformula, and this large-grid route is deeper material.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Plain recursion | 2 x paths - 1 calls x O(1) | O(C(m+n-2, m-1)) | O(m + n) call depth |
| Memoized | (m-1)(n-1) interior states x O(1) | O(mn) | O(mn) plus O(m + n) depth |
| Table | mn cells x O(1) | O(mn) | O(mn) |
| One row | mn updates x O(1) | O(mn) | O(n) |
Closed form with math.comb | one binomial coefficient | depends on the size of the big integers involved | O(1) extra |
To get O(min(m, n)) space, make the row the shorter dimension.
Common mistakes
- Sweeping the single row right to left.
- Treating a one-row or one-column grid as a special case that needs work; the answer is 1, as the 1 x 5 row of the table shows.
Running the code
python3.12 grid_paths.py
Standard library only. Save the listing as grid_paths.py and run the command above; it prints exactly the output shown.
Given an integer array, find the contiguous subarray with the largest sum and return the sum together with its start and end indices. Explain the DP state and transition behind your O(n) solution, and what you do when every element is negative.
Sample Answer
The idea
The best subarray must end somewhere. For each possible end position, keep the best sum of a subarray that ends exactly there. That value either starts fresh at the current element or extends the best run that ended one step earlier, and extending is worth it only if that earlier run is not negative. The final answer is the largest of these n values. This is Kadane's algorithm, and it is a dynamic programming (DP) solution because each value is built from the previous one.
The five things to state
- What one cell means.
ending_here[i]is the largest sum of a non-empty contiguous subarray that must end at index i and includenums[i]. - The transition.
ending_here[i] = max(nums[i], ending_here[i-1] + nums[i]). A subarray ending at i is either justnums[i]or a subarray ending at i-1 withnums[i]appended; the best of the second kind isending_here[i-1] + nums[i]. Extending beats restarting exactly whenending_here[i-1]is positive, and ties when it is 0. - Base case.
ending_here[0] = nums[0]. - Fill order. Left to right, because cell i reads cell i-1.
- Where the answer is. The maximum over all cells, not the last cell. The best run can end anywhere, as the table below shows (the best value 6 sits at index 6 while the last cell is 5).
Brute force first
Try every pair (left, right) and keep a running sum as the right end moves: n(n+1)/2 pairs, which is 45 pairs for 9 numbers, so O(n^2) time and O(1) space. The recurrence above removes the inner loop because the best sum ending at i reuses the best sum ending at i-1.
The code
import random
def max_subarray_brute(nums):
"""Try every (left, right) pair, extending the sum one element at a time."""
best, pairs = None, 0
for left in range(len(nums)):
total = 0
for right in range(left, len(nums)):
pairs += 1
total += nums[right]
if best is None or total > best[0]:
best = (total, left, right)
return best, pairs
def max_subarray_zero_start(nums):
"""Common bug: best starts at 0, which silently allows an empty subarray."""
best = ending_here = 0
for x in nums:
ending_here = max(x, ending_here + x)
best = max(best, ending_here)
return best
def end_table(nums):
"""ending_here[i] = best sum of a subarray that must end at index i."""
ending_here = []
for i, x in enumerate(nums):
ending_here.append(x if i == 0 else max(x, ending_here[-1] + x))
return ending_here
def max_subarray(nums, trace=False):
if not nums:
raise ValueError("need at least one element")
best_sum = ending_here = nums[0]
best_left = best_right = start = 0
for i in range(1, len(nums)):
if ending_here < 0: # carrying a negative sum only hurts
ending_here, start = nums[i], i
else:
ending_here += nums[i]
if ending_here > best_sum: # strict: the earliest best wins
best_sum, best_left, best_right = ending_here, start, i
if trace:
print(f" i={i} x={nums[i]:2d} ending_here={ending_here:2d} start={start} best_sum={best_sum} best_left={best_left} best_right={best_right}")
return best_sum, best_left, best_right
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("filled table:", end_table(nums))
print("brute force:", max_subarray_brute(nums))
print("linear scan:", max_subarray(nums))
print("bookkeeping after each index (index 0 starts everything at nums[0] = -2):")
max_subarray(nums, trace=True)
print("all negative [-3, -1, -2]:", max_subarray([-3, -1, -2]))
print("best initialised to 0 on [-3, -1, -2]:", max_subarray_zero_start([-3, -1, -2]), "(wrong)")
print("one element [7]:", max_subarray([7]))
print("ties [1, -1, 1]:", max_subarray([1, -1, 1]), "| zeros [0, 0]:", max_subarray([0, 0]))
try:
max_subarray([])
except ValueError as e:
print("empty input:", e)
random.seed(2)
for _ in range(500):
n = random.randint(1, 14)
nums = [random.randint(-6, 6) for _ in range(n)]
total, left, right = max_subarray(nums)
assert total == max_subarray_brute(nums)[0][0] == max(end_table(nums))
assert sum(nums[left:right + 1]) == total and 0 <= left <= right < n
print("500 random arrays: value matches brute force and nums[left..right] sums to it")
Output:
filled table: [-2, 1, -2, 4, 3, 5, 6, 1, 5]
brute force: ((6, 3, 6), 45)
linear scan: (6, 3, 6)
bookkeeping after each index (index 0 starts everything at nums[0] = -2):
i=1 x= 1 ending_here= 1 start=1 best_sum=1 best_left=1 best_right=1
i=2 x=-3 ending_here=-2 start=1 best_sum=1 best_left=1 best_right=1
i=3 x= 4 ending_here= 4 start=3 best_sum=4 best_left=3 best_right=3
i=4 x=-1 ending_here= 3 start=3 best_sum=4 best_left=3 best_right=3
i=5 x= 2 ending_here= 5 start=3 best_sum=5 best_left=3 best_right=5
i=6 x= 1 ending_here= 6 start=3 best_sum=6 best_left=3 best_right=6
i=7 x=-5 ending_here= 1 start=3 best_sum=6 best_left=3 best_right=6
i=8 x= 4 ending_here= 5 start=3 best_sum=6 best_left=3 best_right=6
all negative [-3, -1, -2]: (-1, 1, 1)
best initialised to 0 on [-3, -1, -2]: 0 (wrong)
one element [7]: (7, 0, 0)
ties [1, -1, 1]: (1, 0, 0) | zeros [0, 0]: (0, 0, 0)
empty input: need at least one element
500 random arrays: value matches brute force and nums[left..right] sums to it
Reading the output
- The filled table
[-2, 1, -2, 4, 3, 5, 6, 1, 5]isending_herefor the sample. At index 2 the running value is -2, which is negative, so at index 3 the code restarts with4. The maximum is 6 at index 6, and the start recorded when the run restarted is 3, so the answer is(6, 3, 6), the subarray4, -1, 2, 1. The brute force finds the same triple after checking 45 pairs. - Tracking indices.
startchanges only when the running sum before the current element is negative.best_leftandbest_rightare copied fromstartand i only when a strictly larger sum is found. The bookkeeping lines in the output show this: at i = 1 the carried sum -2 is negative, so the run restarts and start becomes 1; at i = 2 the sum is -2 again, still below best_sum, so nothing is copied; at i = 3 the carried sum is -2 (negative), so the run restarts at 3 with value 4, which beats the best so far, so best_left and best_right become 3 and 3. From i = 4 to 6 the run extends (start stays 3) and best_right moves to 5, then 6 as the sum reaches 5, then 6; at i = 7 and 8 the sum is 1 and 5, never above 6, so the best stays (6, 3, 6). - Ties. The strict
>keeps the earliest best subarray:[1, -1, 1]returns(1, 0, 0), not(1, 0, 2)or(1, 2, 2). A running sum of exactly 0 is extended rather than restarted, so zeros stay attached to a run that continues. The run on[0, 0]returns(0, 0, 0). - All elements negative. The answer is the largest single element, with its index:
[-3, -1, -2]gives(-1, 1, 1). Initialising the best to 0 returns 0 here, which silently allows an empty subarray; the driver shows that wrong result. - An empty array has no non-empty subarray, so the code raises
ValueError(printed above). - The check compares the value with the brute force on 500 seeded arrays and verifies that
nums[left..right]really sums to the reported value.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Brute force over (left, right) | n(n+1)/2 pairs x O(1) | O(n^2) | O(1) |
Table ending_here | n states x O(1) | O(n) | O(n) |
| Shipped scan (one running value) | n steps x O(1) | O(n) | O(1) |
Space drops to O(1) because cell i reads only cell i-1. The scan must go forward for that reason: the running value at step i is only meaningful once step i-1 has produced it. Python integers never overflow. In a fixed-width language (one whose integers have a set size such as 32 or 64 bits) the sum can overflow, meaning it grows past the largest value the type can hold and then wraps around (Java) or is undefined behaviour (signed integers in C), when n times the largest value exceeds the integer range, so use a 64-bit sum.
Common mistakes
- Reading the last cell instead of the maximum over all cells.
- Resetting to 0 instead of to
nums[i], which breaks the all-negative case. - Moving
startwhen the sum is merely lower than the best so far, rather than when the running sum before the element is negative.
Running the code
python3.12 max_subarray.py
Standard library only. Save the listing as max_subarray.py and run the command above; it prints exactly the output shown.
A row of houses holds nums[i] dollars each, and you cannot take from two adjacent houses. Return the maximum total you can take in O(n) time. Define the state, the transition and the base cases, and then reduce the space to O(1).
Sample Answer
The idea
At each house you either skip it or take it. If you take house i you cannot have taken house i-1, so the best you can add to it is the best total over houses before i-1. If you skip it, you keep the best total over houses before i. The better of the two is the best total so far, and it only ever depends on the previous two best totals. That is a dynamic programming (DP) solution: a problem solved by combining the answers to smaller versions of itself that overlap.
Numbering used throughout: the houses are nums[0], nums[1], and so on, counted from 0, so "house 2" is nums[2]. The table best is counted differently on purpose: best[i] covers the first i houses, so the last house it includes is house i-1, and that is why the transition below reads nums[i-1].
The five things to state
- What one cell means.
best[i]is the largest total you can take from the first i houses (houses 0 to i-1), with no two adjacent. - The transition.
best[i] = max(best[i-1], best[i-2] + nums[i-1]). The first term skips house i-1; the second takes it, which forces you to skip house i-2 and fall back tobest[i-2]. Every legal choice falls under exactly one of the two terms. - Base cases.
best[0] = 0(no houses) andbest[1] = max(0, nums[0]). Taking no house at all is a legal plan worth 0, so no answer is ever below 0. With non-negative values themax(0, ...)changes nothing; with a negative value it lets you skip the house. - Fill order. Ascending i, since each cell reads
best[i-1]andbest[i-2]. - Where the answer is.
best[n].
Brute force first
The recursion f(i) = max(f(i+1), nums[i] + f(i+2)) tries both choices at every house. Counting calls on [1] * n gives 25 calls for n = 5, 287 for n = 10, 35,421 for n = 20 and 392,835 for n = 25, growing by about a factor of 1.6 per house. Memoizing on i brings that to 2n + 1 calls (11, 21, 41, 51 in the table below), because there are only n + 1 distinct values of i.
The code
import itertools
import random
def rob_brute(nums):
"""Try every subset with no two adjacent houses."""
best = 0
for mask in range(1 << len(nums)):
if mask & (mask >> 1):
continue
best = max(best, sum(v for i, v in enumerate(nums) if mask >> i & 1))
return best
calls = 0
def rob_recursive(nums, i=0):
"""f(i) = best from houses i.. : skip house i, or take it and jump to i+2."""
global calls
calls += 1
if i >= len(nums):
return 0
return max(rob_recursive(nums, i + 1), nums[i] + rob_recursive(nums, i + 2))
def rob_memo(nums):
memo, count = {}, [0]
def f(i):
count[0] += 1
if i >= len(nums):
return 0
if i not in memo:
memo[i] = max(f(i + 1), nums[i] + f(i + 2))
return memo[i]
return f(0), count[0]
def rob_table(nums):
"""best[i] = most you can take from the first i houses."""
best = [0] * (len(nums) + 1)
if nums:
best[1] = max(0, nums[0])
for i in range(2, len(nums) + 1):
best[i] = max(best[i - 1], best[i - 2] + nums[i - 1])
return best
def rob(nums):
two_back, one_back = 0, 0 # best[i-2], best[i-1]
for value in nums:
two_back, one_back = one_back, max(one_back, two_back + value)
return one_back
def rob_wrong(nums):
two_back, one_back = 0, 0
for value in nums:
two_back = one_back # overwritten before it is used
one_back = max(one_back, two_back + value)
return one_back
nums = [2, 7, 9, 3, 1]
print("filled table:", rob_table(nums))
calls = 0
print("recursion:", rob_recursive(nums), "calls:", calls, "| memo:", rob_memo(nums))
print("O(1)-space:", rob(nums), "| wrong update order:", rob_wrong(nums))
for n in (5, 10, 20, 25):
calls = 0
rob_recursive([1] * n)
print(f"n={n:2d} recursion calls={calls:6d} memo calls={rob_memo([1] * n)[1]}")
print("empty:", rob([]), "one house:", rob([4]), "two houses:", rob([3, 8]), "all zeros:", rob([0, 0, 0]))
print("[4, 5, 4]:", rob([4, 5, 4]), "(taking the largest house alone gives 5)")
print("with a negative value:", rob([5, -2, 4]), "(taking is optional)")
print("\nsubsets of 3 houses as bitmasks (bit i is 1 when house i is taken):")
print("mask mask>>1 mask & (mask>>1) allowed")
for mask in range(8):
print(f"{mask:03b} {mask >> 1:03b} {mask & (mask >> 1):03b} {not mask & (mask >> 1)}")
random.seed(11)
for _ in range(400):
n = random.randint(0, 12)
nums = [random.randint(-5, 20) for _ in range(n)]
expected = rob_brute(nums)
assert rob(nums) == rob_table(nums)[n] == rob_memo(nums)[0] == rob_recursive(nums) == expected
print("400 random arrays (length 0..12, values -5..20) agree with subset enumeration")
Output:
filled table: [0, 2, 7, 11, 11, 12]
recursion: 12 calls: 25 | memo: (12, 11)
O(1)-space: 12 | wrong update order: 22
n= 5 recursion calls= 25 memo calls=11
n=10 recursion calls= 287 memo calls=21
n=20 recursion calls= 35421 memo calls=41
n=25 recursion calls=392835 memo calls=51
empty: 0 one house: 4 two houses: 8 all zeros: 0
[4, 5, 4]: 8 (taking the largest house alone gives 5)
with a negative value: 9 (taking is optional)
subsets of 3 houses as bitmasks (bit i is 1 when house i is taken):
mask mask>>1 mask & (mask>>1) allowed
000 000 000 True
001 000 000 True
010 001 000 True
011 001 001 False
100 010 000 True
101 010 000 True
110 011 010 False
111 011 011 False
400 random arrays (length 0..12, values -5..20) agree with subset enumeration
Reading the output
- The filled table
[0, 2, 7, 11, 11, 12]isbest[0]tobest[5]for[2, 7, 9, 3, 1]. The cellbest[3] = 11covers the first three houses (houses 0, 1 and 2). It came from taking house 2 (nums[2], value 9) plusbest[1] = 2, the best over house 0 alone;best[4] = 11is the skip branch because taking the 3 (house 3) would give onlybest[2]+ 3 = 7 + 3 = 10. - Constant space: each step reads only
best[i-1]andbest[i-2], sotwo_backandone_backreplace the list. The assignment must be simultaneous. The wrong version first setstwo_back = one_backand then computesmax(one_back, two_back + value), which isone_back + value, so it adds every house together and prints 22 instead of 12. - The empty array returns 0, one house returns its value, and two houses return the larger one. A negative value is simply never taken, because skipping is always allowed.
- The subset check in
rob_brutewrites each choice of houses as a bitmask, an integer whose bit i is 1 when house i is taken (bit 0 is the rightmost).mask >> i & 1shifts the mask right by i places and keeps the last bit, which reads bit i.mask >> 1slides every bit one place right, so bit i of the shifted copy equals bit i+1 of the original; ANDing the two withmask & (mask >> 1)is nonzero exactly when some bit i and bit i+1 are both 1, that is, two neighbouring houses are taken. The printed table lists all 8 masks for 3 houses:011,110and111are rejected and the other five are allowed. - The check compares the table, the memoized recursion, the plain recursion and the two-variable loop with a brute force over every subset that has no two adjacent houses, on 400 seeded arrays of length 0 to 12 with values from -5 to 20.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Plain recursion | about 1.6^n calls x O(1) | exponential | O(n) call depth |
| Memoized | n + 1 states x O(1) | O(n) | O(n) |
| Table | n + 1 cells x O(1) | O(n) | O(n) |
| Two variables | n steps x O(1) | O(n) | O(1) |
Common mistakes
- Greedy fails: on
[4, 5, 4]taking the largest house gives 5, while houses 0 and 2 give 8, as the driver prints. Prove the transition rather than testing one example. - Using
best[i-1] + nums[i](forgetting the adjacency rule) orbest[i-3](assuming you must skip two houses). - Reading
nums[0]without checking for an empty array. - Overwriting the rolling variable before it is used, as shown above.
Running the code
python3.12 house_robber.py
Standard library only. Save the listing as house_robber.py and run the command above; it prints exactly the output shown.
Given coin denominations and a target amount, with unlimited coins of each kind, return the fewest coins that make the amount, or -1 if it is impossible. Define the state, recurrence and initialization, give the time and space cost, and then show how to recover the actual coins used.
Sample Answer
The idea
To make amount a with the fewest coins, think about the last coin you hand over. If it has value c, what you handed over before it made exactly a - c, and you want that earlier part to use as few coins as possible. Trying every coin as the last one and taking the best gives a formula that reuses answers for smaller amounts. Greedy (always take the biggest coin that fits) can fail, so this needs dynamic programming (DP): solving small versions first and combining them.
The five things to state
- What one cell means.
fewest[a]is the minimum number of coins that sum to exactly a, or infinity if no combination makes a. - The transition.
fewest[a] = 1 + min(fewest[a - c])over every coin c with c <= a. The 1 is the last coin, andfewest[a - c]is the best way to build the rest. Taking the minimum over all choices of the last coin covers every possible solution. - Base case and initialisation.
fewest[0] = 0(no coins make zero). Every other cell starts at infinity, meaning "not reachable yet". Infinity plus 1 is still infinity, so a coin that leads to an unreachable remainder can never win a minimum. - Fill order. Ascending a, because cell a reads smaller cells
a - c. - Where the answer is.
fewest[amount]. If it is still infinity, return -1.
Why the initial value matters
Starting the unreachable cells at 0 treats "impossible" as "free". The driver runs that bug: for coins [2] and amount 3 it prints 1 instead of -1, because fewest[1] stays 0 and the code believes one coin of 2 reaches 3. Starting at -1 fails the opposite way, because min would pick -1 and then add 1 to get 0. With integer infinity (or amount + 1 as a stand-in for infinity: every real answer uses at most amount coins because each coin is worth at least 1, so amount + 1 can never be a genuine count), unreachable amounts are detected by one comparison at the end.
Brute force first
Plain recursion tries every coin from every remainder. For coins [1, 2, 5] and amount 11 it makes 527 calls. With a cache keyed on the remainder it makes 29 calls, because only the 12 remainders 0 to 11 exist. The table version fills those 12 cells directly.
Recovering the coins
Alongside fewest, keep last_coin[a], the coin that gave the current best for a. It is written exactly when fewest[a] improves. After filling, start at the target amount, append last_coin[a], subtract it and repeat until the amount reaches 0. The walk takes fewest[amount] steps.
The code
import random
INF = float("inf")
def coins_brute(coins, amount):
calls = [0]
def go(rest):
calls[0] += 1
if rest == 0:
return 0
best = INF
for c in coins:
if c <= rest:
best = min(best, 1 + go(rest - c))
return best
result = go(amount)
return (-1 if result == INF else result), calls[0]
def coins_memo(coins, amount):
memo, calls = {}, [0]
def go(rest):
calls[0] += 1
if rest == 0:
return 0
if rest not in memo:
memo[rest] = min((1 + go(rest - c) for c in coins if c <= rest), default=INF)
return memo[rest]
result = go(amount)
return (-1 if result == INF else result), calls[0]
def coin_change(coins, amount):
"""fewest[a] = fewest coins that sum to exactly a. Returns (count, coins used)."""
if amount < 0 or any(c <= 0 for c in coins):
raise ValueError("amount must be >= 0 and coins positive")
fewest = [INF] * (amount + 1)
last_coin = [0] * (amount + 1)
fewest[0] = 0
for a in range(1, amount + 1):
for c in coins:
if c <= a and fewest[a - c] + 1 < fewest[a]:
fewest[a] = fewest[a - c] + 1
last_coin[a] = c
if fewest[amount] == INF:
return -1, []
used, a = [], amount
while a > 0:
used.append(last_coin[a])
a -= last_coin[a]
return fewest[amount], used
def coin_change_table(coins, amount):
fewest = [INF] * (amount + 1)
fewest[0] = 0
for a in range(1, amount + 1):
fewest[a] = min((fewest[a - c] + 1 for c in coins if c <= a), default=INF)
return fewest
def coin_change_each_coin_once(coins, amount):
"""Same table, but amounts visited high to low: every coin can be used at most once."""
fewest = [INF] * (amount + 1)
fewest[0] = 0
for c in coins:
for a in range(amount, c - 1, -1):
fewest[a] = min(fewest[a], fewest[a - c] + 1)
return -1 if fewest[amount] == INF else fewest[amount]
def coin_change_zero_init(coins, amount):
fewest = [0] * (amount + 1) # wrong: 0 means "free", not "unreachable"
for a in range(1, amount + 1):
fewest[a] = min((fewest[a - c] + 1 for c in coins if c <= a), default=0)
return fewest[amount]
coins, amount = [1, 2, 5], 11
print("filled table:", coin_change_table(coins, amount))
print("answer and coins:", coin_change(coins, amount))
print("plain recursion (answer, calls):", coins_brute(coins, amount))
print("memoized (answer, calls):", coins_memo(coins, amount))
print("impossible [2], 3:", coin_change([2], 3), "| amount 0:", coin_change([1, 2], 0))
print("zero-initialised table on [2], 3:", coin_change_zero_init([2], 3), "(should be -1)")
print("each coin once on [1, 2, 5], 11:", coin_change_each_coin_once([1, 2, 5], 11), "(unlimited gives 3)")
print("greedy takes 4+1+1 for [1, 3, 4], 6 (3 coins); DP:", coin_change([1, 3, 4], 6))
try:
coin_change([0, 2], 4)
except ValueError as e:
print("bad input:", e)
random.seed(9)
for _ in range(400):
coins = random.sample(range(1, 10), random.randint(1, 4))
amount = random.randint(0, 22)
count, used = coin_change(coins, amount)
assert count == coins_brute(coins, amount)[0] == coins_memo(coins, amount)[0]
if count >= 0:
assert len(used) == count and sum(used) == amount and set(used) <= set(coins)
print("400 random cases match brute force; recovered coins sum to the amount")
Output:
filled table: [0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2, 3]
answer and coins: (3, [1, 5, 5])
plain recursion (answer, calls): (3, 527)
memoized (answer, calls): (3, 29)
impossible [2], 3: (-1, []) | amount 0: (0, [])
zero-initialised table on [2], 3: 1 (should be -1)
each coin once on [1, 2, 5], 11: -1 (unlimited gives 3)
greedy takes 4+1+1 for [1, 3, 4], 6 (3 coins); DP: (2, [3, 3])
bad input: amount must be >= 0 and coins positive
400 random cases match brute force; recovered coins sum to the amount
Reading the output
- The filled table for
[1, 2, 5]isfewest[0..11]: for examplefewest[10] = 2(5 + 5) andfewest[11] = 3. The recovered coins[1, 5, 5]sum to 11 and there are 3 of them, matching the table. Because coins are tried in list order and only a strictly better count replaces a cell, ties keep the first coin that reached the best value. [2]with amount 3 returns(-1, []), and amount 0 returns(0, []).- For
[1, 3, 4]and amount 6 greedy would pay 4 + 1 + 1 (3 coins), while the DP finds 3 + 3 (2 coins). - Direction. The shipped loops visit each amount after all smaller ones, so any coin can be reused. The
coin_change_each_coin_oncevariant puts coins on the outside and walks the amounts downwards, so cella - cstill holds the value from before this coin was considered and the coin is used at most once. On[1, 2, 5]and amount 11 it returns -1, because 1 + 2 + 5 = 8 is the most that three single coins can make. Walking upwards in that layout instead lets a coin be reused. The same upward-versus-downward choice is the whole difference between unbounded problems (each item may be used any number of times) and 0/1 problems (each item is used zero or one times); the section on coin systems prints the rows for both on a small input. - Non-positive coins and negative amounts raise
ValueError(the driver triggers it with a coin of 0). - The check compares the value with brute force on 400 seeded cases and verifies that the recovered coins sum to the amount, number
fewest[amount]and come from the coin list.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Plain recursion | up to k^(amount / smallest coin) paths | exponential | O(amount) call depth |
| Memoized | amount + 1 states x k coins | O(amount x k) | O(amount) |
| Table with reconstruction | amount + 1 cells x k coins | O(amount x k) | O(amount) for fewest and last_coin |
Here k is the number of denominations. Reconstruction adds O(fewest[amount]) time and needs the last_coin array; the value alone needs only fewest.
Which coin systems greedy handles, and the each-coin-once table
A coin system is canonical when greedy (always take the largest coin that fits) gives the fewest coins for every amount; the DP does not need that property. The program below searches amounts up to 200 for a counterexample on two systems. It then prints the table row after each coin for the each-coin-once layout (outer loop over coins, inner loop over amounts), once with the amounts walked from high to low and once from low to high, on coins [2, 3] and amount 6.
INF = float("inf")
def fewest_table(coins, amount):
fewest = [INF] * (amount + 1)
fewest[0] = 0
for a in range(1, amount + 1):
fewest[a] = min((fewest[a - c] + 1 for c in coins if c <= a), default=INF)
return fewest
def greedy_count(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count if amount == 0 else INF
def first_greedy_failure(coins, limit):
table = fewest_table(coins, limit)
for a in range(1, limit + 1):
if greedy_count(coins, a) != table[a]:
return a, greedy_count(coins, a), table[a]
return None
print("[1, 5, 10, 25] first amount up to 200 where greedy is not optimal:", first_greedy_failure([1, 5, 10, 25], 200))
print("[1, 3, 4] first (amount, greedy coins, optimal coins):", first_greedy_failure([1, 3, 4], 200))
def show(row):
return "[" + ", ".join("inf" if v == INF else str(v) for v in row) + "]"
def each_coin_rows(coins, amount, descending):
fewest = [INF] * (amount + 1)
fewest[0] = 0
print(" start ", show(fewest))
for c in coins:
for a in (range(amount, c - 1, -1) if descending else range(c, amount + 1)):
fewest[a] = min(fewest[a], fewest[a - c] + 1)
print(f" after coin {c}:", show(fewest))
print("coins [2, 3], amount 6, each coin at most once (amounts high to low):")
each_coin_rows([2, 3], 6, descending=True)
print("same layout with amounts low to high (a coin can be reused):")
each_coin_rows([2, 3], 6, descending=False)
Output:
[1, 5, 10, 25] first amount up to 200 where greedy is not optimal: None
[1, 3, 4] first (amount, greedy coins, optimal coins): (6, 3, 2)
coins [2, 3], amount 6, each coin at most once (amounts high to low):
start [0, inf, inf, inf, inf, inf, inf]
after coin 2: [0, inf, 1, inf, inf, inf, inf]
after coin 3: [0, inf, 1, 1, inf, 2, inf]
same layout with amounts low to high (a coin can be reused):
start [0, inf, inf, inf, inf, inf, inf]
after coin 2: [0, inf, 1, inf, 2, inf, 3]
after coin 3: [0, inf, 1, 1, 2, 2, 2]
Read the high-to-low rows: after coin 2 only the amount 2 became reachable (cell 4 stays inf, since a second 2 is not allowed), and after coin 3 the amounts 3 and 5 appear. In the low-to-high rows the same coin 2 fills cells 2, 4 and 6 with 1, 2 and 3 coins because each cell reads the cell just updated with the same coin, which is reuse.
Common mistakes
- Initialising unreachable cells to 0 or -1, shown above.
- Using greedy without proving the coin system is canonical (greedy-optimal for every amount). The search up to 200 in the coin-systems section finds the counterexample for
[1, 3, 4], but finding none for[1, 5, 10, 25]is a check on those amounts, not a proof. - Returning
fewest[amount]without mapping infinity to -1.
Running the code
python3.12 coin_change_min.py
Standard library only. Save the first listing as coin_change_min.py and run the command above; it prints exactly the output shown. The listing in the coin-systems section is a separate file, canonical_and_once.py, run the same way, and it prints the second output block.
Given a string s and a dictionary of words, decide whether s can be split into a space-separated sequence of dictionary words. Walk through your state and recurrence, give the complexity, and say how it changes if the dictionary is very large or you must return every valid segmentation.
Sample Answer
The idea
Splitting a string into dictionary words is a chain of decisions about where one word ends and the next begins. Whether a whole string can be split depends only on whether some shorter prefix can be split and the leftover piece is a word. So the question "can the first i characters be split?" reuses the same question for smaller i, and that overlap is what dynamic programming (DP) exploits. The brute force tries every first word at every position and repeats the same suffixes enormously often.
The five things to state
- What one cell means.
ok[i]is True when the prefixs[:i](the first i characters) can be split into dictionary words. A cell is a prefix length, so the table has n + 1 cells. - The transition.
ok[i]is True if some j < i hasok[j]True ands[j:i]in the dictionary. The words[j:i]is the last word andok[j]says everything before it is fine, so every split of the prefix is covered by exactly one choice of last word. - Base case.
ok[0] = True, the empty prefix, so a word that starts at the beginning can be accepted. - Fill order. Ascending i, because
ok[i]reads smaller indices. - Where the answer is.
ok[n].
lru_cache(maxsize=None) in the code is a decorator (a wrapper placed above a function) that remembers the result for each distinct argument: a later call with the same start returns the stored value without running the body again.
The memoized recursion uses the mirror-image state: go(start) asks whether the suffix s[start:] can be split, and the memo key is the integer start. There are only n + 1 possible keys, which is what makes it fast.
The expression any(s.startswith(w, start) and go(start + len(w)) for w in words) is a compact loop. s.startswith(w, start) asks whether the text beginning at index start starts with w, without copying a slice. and evaluates go(...) only when that is True. any consumes the generator one item at a time and stops at the first True, so the remaining words are never tried. can_break_memo_loops in the code is the same function written as an explicit for loop with an early return True, and the random check asserts they agree.
The code
import random
from functools import lru_cache
def can_break_brute(s, words):
calls = [0]
def go(start):
calls[0] += 1
if start == len(s):
return True
return any(s.startswith(w, start) and go(start + len(w)) for w in words)
return go(0), calls[0]
def can_break_memo(s, words):
calls = [0]
@lru_cache(maxsize=None)
def go(start):
calls[0] += 1
if start == len(s):
return True
return any(s.startswith(w, start) and go(start + len(w)) for w in words)
return go(0), calls[0]
def can_break_memo_loops(s, words):
"""can_break_memo written with an explicit loop; same answer."""
@lru_cache(maxsize=None)
def go(start):
if start == len(s):
return True
for w in words:
if s.startswith(w, start): # does s[start:] begin with w?
if go(start + len(w)):
return True # first success ends the search, like any()
return False
return go(0)
def can_break(s, words):
"""ok[i] is True when the prefix s[:i] splits into dictionary words."""
word_set = set(words)
max_len = max(map(len, word_set), default=0)
ok = [False] * (len(s) + 1)
ok[0] = True # empty prefix
for i in range(1, len(s) + 1):
for j in range(max(0, i - max_len), i): # last word is s[j:i]
if ok[j] and s[j:i] in word_set:
ok[i] = True
break
return ok
def all_breaks(s, words):
word_set = set(words)
max_len = max(map(len, word_set), default=0)
memo = {}
def sentences(start): # every split of s[start:]
if start == len(s):
return [[]]
if start not in memo:
out = []
for end in range(start + 1, min(len(s), start + max_len) + 1):
if s[start:end] in word_set:
out += [[s[start:end]] + rest for rest in sentences(end)]
memo[start] = out
return memo[start]
return [" ".join(parts) for parts in sentences(0)]
class Trie:
def __init__(self, words):
self.root = {}
for w in words:
node = self.root
for ch in w:
node = node.setdefault(ch, {})
node["$"] = True
def can_break(self, s, trace=False):
ok = [False] * (len(s) + 1)
ok[0] = True
for j in range(len(s)):
if not ok[j]:
continue # no split ends at j, so no word may start there
node = self.root
for i in range(j, len(s)): # walk s[j:] down the trie
node = node.get(s[i])
if node is None:
if trace:
print(f" start {j}: no word continues with {s[j:i + 1]!r}")
break
if "$" in node: # a word ends at character i, so prefix length i + 1 works
ok[i + 1] = True
if trace:
print(f" start {j}: word {s[j:i + 1]!r} ends here, ok[{i + 1}] = True")
return ok
s, words = "catsanddog", ["cat", "cats", "and", "sand", "dog"]
print("prefix table:", can_break(s, words))
print("segmentations:", all_breaks(s, words))
print("trie for ['cat', 'cats', 'and']:", Trie(["cat", "cats", "and"]).root)
print("trie walk on", s)
print("trie table: ", Trie(words).can_break(s, trace=True))
print("no split:", can_break("catsandog", words)[-1], "| empty string:", can_break("", words)[-1],
"| empty dictionary on 'abc':", can_break("abc", [])[-1])
bad = "a" * 20 + "b"
bad_words = ["a", "aa", "aaa"]
print("pathological input, plain recursion:", can_break_brute(bad, bad_words))
print("pathological input, memo on start index:", can_break_memo(bad, bad_words))
print("segmentations of 'a'*n with {a, aa} for n=5, 10, 20:",
[len(all_breaks("a" * n, ["a", "aa"])) for n in (5, 10, 20)])
random.seed(5)
def rand_word(): return "".join(random.choice("ab") for _ in range(random.randint(1, 3)))
for _ in range(400):
words = list({rand_word() for _ in range(random.randint(1, 4))})
s = "".join(random.choice("ab") for _ in range(random.randint(0, 11)))
expected = can_break_brute(s, words)[0]
assert can_break(s, words)[-1] == can_break_memo(s, words)[0] == can_break_memo_loops(s, words) == Trie(words).can_break(s)[-1] == expected
segs = all_breaks(s, words)
assert bool(segs) == expected
assert all("".join(x.split()) == s and set(x.split()) <= set(words) for x in segs)
assert len(segs) == len(set(segs))
print("400 random cases agree with brute force; every returned segmentation rebuilds s")
Output:
prefix table: [True, False, False, True, True, False, False, True, False, False, True]
segmentations: ['cat sand dog', 'cats and dog']
trie for ['cat', 'cats', 'and']: {'c': {'a': {'t': {'$': True, 's': {'$': True}}}}, 'a': {'n': {'d': {'$': True}}}}
trie walk on catsanddog
start 0: word 'cat' ends here, ok[3] = True
start 0: word 'cats' ends here, ok[4] = True
start 0: no word continues with 'catsa'
start 3: word 'sand' ends here, ok[7] = True
start 3: no word continues with 'sandd'
start 4: word 'and' ends here, ok[7] = True
start 4: no word continues with 'andd'
start 7: word 'dog' ends here, ok[10] = True
trie table: [True, False, False, True, True, False, False, True, False, False, True]
no split: False | empty string: True | empty dictionary on 'abc': False
pathological input, plain recursion: (False, 266079)
pathological input, memo on start index: (False, 21)
segmentations of 'a'*n with {a, aa} for n=5, 10, 20: [8, 89, 10946]
400 random cases agree with brute force; every returned segmentation rebuilds s
Reading the output
prefix tablehas True at positions 0, 3, 4, 7 and 10 forcatsanddog. Position 7 iscatsand, reachable ascat+sandand ascats+and; position 10 closes both splits withdog, so the two segmentations printed come from those two routes.catsandogreturns False: the prefixcatsandis fine but the leftoverogis not a word.- The trie version (a tree where each edge is a letter and a marked node ends a word) gives the same table. Each node is a dictionary from a letter to the child node (a dict of dicts), and
node.setdefault(ch, {})returns the existing child forchor creates an empty one, so words that share a start share nodes. The key"$"is not a letter: it is a sentinel (a marker value) meaning "a dictionary word ends at this node". The printed trie forcat,catsandandshowscatandcatssharing the path c, a, t, with"$"att(socatends there) and a furtherschild holding another"$". - Reading the trie walk: the outer loop picks a start
jwhereok[j]is True, the inner loop walks one character at a time down the trie, andok[i + 1]is set the moment a word ends at characteri, because the prefix up to and including that character has lengthi + 1. Start 0 findscat(setsok[3]) andcats(setsok[4]); starts 3 and 4 findsandandandwhich both setok[7]; start 7 findsdogand setsok[10]. A start that fails prints where the trie ran out of matching letters. - On
aaaaaaaaaaaaaaaaaaaabwith words a, aa and aaa, the answer is False, and the plain recursion makes 266,079 calls to find that out, because every route through the a's is retried. The memoized body runs once per start index, 21 times. Memo key and pathological input go together: any input where many different splits reach the same position punishes the plain version. - Word Break II uses the same memo on
startbut stores lists of sentences. On a string of a's with words a and aa the number of segmentations is 8, 89 and 10,946 for n = 5, 10 and 20: these are Fibonacci numbers, so the output itself can be exponentially large. - The random check compares the table, the memoized recursion and the trie against the plain recursion on 400 seeded cases and checks that every returned sentence rebuilds
sfrom dictionary words.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Plain recursion | up to exponentially many calls | exponential in the worst case | O(n) call depth |
Memoized, key start | n + 1 states x up to | D | words |
| Set table (shipped) | n + 1 cells x at most L splits x O(L) slice and hash | O(n x L^2) | O(n) plus the set |
| Trie table | n + 1 starts x at most L steps | O(n x L) | O(n) plus the trie |
| Word Break II | n + 1 states, each building lists | proportional to the total output size | proportional to the output |
Here n is the string length, L the length of the longest dictionary word and |D| the number of words. The max_len bound on the inner loop is what makes the cost independent of how many words the dictionary has. Without it the loop is O(n^2) pairs, each costing a slice.
A very large dictionary
Never loop over the dictionary at each position; with a million words that is n x |D| x L work. Keep the words in a hash set and only try end positions up to L away, or walk a trie from each reachable start so that one pass over the next characters tests all words at once and stops the moment no word has that prefix. A trie also shares prefixes, which saves memory when many words share them.
Edge cases and common mistakes
- Empty string: True, because
ok[0]is True (printed above). - Empty dictionary:
max(..., default=0)makes the inner range empty, so every non-empty string is False. - Forgetting the base case
ok[0] = True, so nothing is ever reachable. - Memoizing on the substring instead of the integer
start: it works but hashes and copies strings. - Calling Word Break II without noticing the answer size is itself exponential.
Running the code
python3.12 word_break.py
Standard library only. Save the listing as word_break.py and run the command above; it prints exactly the output shown.
Unlock Full Question Bank
Get access to all 6 Dynamic Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.