Sub topic 11
Tracing back to recover the solution
This chapter assumes you can already fill a one-dimensional and a two-dimensional DP table in Python, and that you know the coin change and longest common subsequence (LCS) recurrences from the earlier chapters. You should also be comfortable with nested lists and simple while loops.
So far every table has answered a "how much" question: the fewest coins, or the length of the longest subsequence. In practice you usually also need the solution itself, meaning which coins to use or which characters form the subsequence. The table already contains enough information to rebuild it. You start at the final cell and walk back to a base case, and at each step you ask which choice in the recurrence produced the value in the current cell.
The general model
Every DP recurrence picks the best of several options. Each option points at one or more earlier states. Once the table is filled, every cell has a value, and at least one of its options produced that value. Tracing back means repeating three steps:
- Start at the state that holds the final answer.
- Find an option whose predecessor value, combined with that option's cost, equals the current cell's value.
- Record that option's contribution, such as a coin or a character, and move to the predecessor.
You stop when you reach a base case. Because each step moves to a strictly smaller state, the walk visits at most one cell per "layer" of the table. In coin change it takes at most amount steps. In LCS it takes at most m + n steps. Reconstruction is almost always much cheaper than filling the table.
You can find the optimal option in two ways.
| Strategy | How it works | Extra memory | When to prefer it |
|---|---|---|---|
| Record choices | Store the winning option in a parallel `choice` table while filling | One more table of the same shape | The recurrence has many options, or checking them again is expensive |
| Re-derive | During traceback, test each option again against the stored values | None | Options are few and cheap to test, and you want to keep memory low |
Both strategies give a valid optimal solution. They can return different solutions when several options tie.
Coin change: recording the choice
Here is the coin change table with a choice list added. choice[a] holds the coin that last improved dp[a].
def min_coins_with_choice(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
choice = [None] * (amount + 1)
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
choice[a] = c
if dp[amount] == INF:
return -1, []
used = []
a = amount
while a > 0:
c = choice[a]
used.append(c)
a -= c
return dp[amount], used
print(min_coins_with_choice([1, 3, 4], 6)) # (2, [3, 3])
print(min_coins_with_choice([2], 3)) # (-1, [])With coins [1, 3, 4] and amount 6, the traceback reads choice[6] = 3, moves to amount 3, reads choice[3] = 3, and reaches 0. A greedy approach that always takes the largest coin would return [4, 1, 1], which uses three coins. The traceback returns the answer the recurrence actually found, so it is guaranteed to be optimal.
The feasibility check comes before the walk for a reason. If dp[amount] is infinite, no path leads back to 0, and choice[amount] is None. Without the check, a -= c would raise a TypeError.
Coin change: re-deriving the choice
If you already have the plain dp list, you can reconstruct the coins without a choice table. At amount a, any coin c with dp[a - c] + 1 == dp[a] lies on an optimal path.
def min_coins_table(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp
def coins_from_table(dp, coins, amount):
if dp[amount] == float('inf'):
return []
used = []
a = amount
while a > 0:
for c in coins:
if c <= a and dp[a - c] + 1 == dp[a]:
used.append(c)
a -= c
break
return used
dp = min_coins_table([1, 3, 4], 6)
print(coins_from_table(dp, [1, 3, 4], 6)) # [3, 3]Each traceback step costs O(k) for k coin types, and there are at most dp[amount] steps. The total is O(k · dp[amount]), which is small next to the O(k · amount) fill.
The same idea works top-down. If best(a) is a function memoized with functools.lru_cache, you walk from amount and pick any coin where best(a - c) + 1 == best(a). Every call during the walk hits the cache, so reconstruction adds no new subproblem work.
LCS: following the arrows
In the LCS table, dp[i][j] is the LCS length of a[:i] and b[:j]. The recurrence has three options, and each one corresponds to a move in the table:
- If
a[i-1] == b[j-1], the character is part of the subsequence. Move diagonally to(i-1, j-1). - Otherwise, if
dp[i-1][j]equalsdp[i][j], move up. - Otherwise,
dp[i][j-1]must equaldp[i][j], so move left.
Characters are collected from the end backward, so the result has to be reversed. The rule for breaking ties between up and left decides which LCS you get when there is more than one.
def lcs_table(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp
def lcs_traceback(a, b, dp, prefer_up=True):
out = []
i, j = len(a), len(b)
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] > dp[i][j - 1] or (
prefer_up and dp[i - 1][j] == dp[i][j - 1]
):
i -= 1
else:
j -= 1
return ''.join(reversed(out))
a, b = "ABC", "ACB"
dp = lcs_table(a, b)
print(lcs_traceback(a, b, dp, prefer_up=True)) # AB
print(lcs_traceback(a, b, dp, prefer_up=False)) # ACAt cell (3, 3) the characters C and B differ, and both neighbors hold 2. Preferring up drops C from a and leads to "AB". Preferring left drops B from b and leads to "AC". Both answers are correct. If your tests compare against one exact string, they are testing the tie-breaking rule as well as the algorithm. Write your tests to check the length and verify that the result is a subsequence of both inputs.
Enumerating every optimal solution
Sometimes you need all optimal solutions, not just one. To get them, follow every move whose predecessor value matches instead of stopping at the first one. Memoizing the walk avoids repeating work on shared cells, but the output itself can grow exponentially with the input length. Use this only on small inputs.
from functools import lru_cache
def all_lcs(a, b):
dp = lcs_table(a, b)
@lru_cache(maxsize=None)
def walk(i, j):
if i == 0 or j == 0:
return frozenset({""})
if a[i - 1] == b[j - 1]:
return frozenset(s + a[i - 1] for s in walk(i - 1, j - 1))
result = set()
if dp[i - 1][j] == dp[i][j]:
result |= walk(i - 1, j)
if dp[i][j - 1] == dp[i][j]:
result |= walk(i, j - 1)
return frozenset(result)
return sorted(walk(len(a), len(b)))
print(all_lcs("ABC", "ACB")) # ['AB', 'AC']The sets remove duplicates. Different paths through the table can spell the same string, and without deduplication the output would count it several times.
A grid path: reconstruction as a list of moves
The value you rebuild does not have to be a set of items. In a minimum-cost grid path, where you can only move right or down, the solution is the route itself. The traceback runs from the bottom-right corner to the top-left corner. On the first row and first column only one move is possible, so those cells need their own cases.
def min_path(grid):
rows, cols = len(grid), len(grid[0])
dp = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
dp[r][c] = grid[0][0]
elif r == 0:
dp[r][c] = dp[r][c - 1] + grid[r][c]
elif c == 0:
dp[r][c] = dp[r - 1][c] + grid[r][c]
else:
dp[r][c] = min(dp[r - 1][c], dp[r][c - 1]) + grid[r][c]
path = []
r, c = rows - 1, cols - 1
while True:
path.append((r, c))
if r == 0 and c == 0:
break
if r == 0:
c -= 1
elif c == 0:
r -= 1
elif dp[r - 1][c] <= dp[r][c - 1]:
r -= 1
else:
c -= 1
path.reverse()
return dp[-1][-1], path
grid = [[1, 3, 1],
[1, 5, 1],
[4, 2, 1]]
print(min_path(grid)) # (7, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Off-by-one between table and input indices | Wrong characters or items in the output | In a table with a padding row and column, cell `(i, j)` refers to `a[i-1]` and `b[j-1]` |
| Forgetting to reverse | Solution comes out backwards | Collect while walking, then reverse once at the end |
| No feasibility check | `TypeError` on `None`, or an infinite loop through infinite values | Check that the final value is finite before walking |
| Tracing a space-optimized table | Traceback reads overwritten values and returns nonsense | Keep the full table or a compact `choice` table. Rolling arrays keep only the last rows, and those rows no longer contain the history |
| Recursive traceback on long inputs | `RecursionError` | Write the walk as a loop. The walk is linear, so a loop is natural |
Exercise
Using min_coins_with_choice, what coin list is returned for coins [1, 5, 6, 9] and amount 11, and why does a greedy approach fail on the same input?
Show answer
The function returns (2, [6, 5]). While filling the table, dp[11] first becomes 3 through coin 1 (dp[10] = 2). Coin 5 then improves it to dp[6] + 1 = 2, so choice[11] = 5. Coin 6 gives dp[5] + 1 = 2, which is not strictly smaller, so the choice stays 5. The walk records 5, moves to amount 6, and reads choice[6] = 6. Collected in walk order, the list is [5, 6]. The function does not reverse it, so it prints [5, 6]. Greedy takes 9, then 1, then 1, which uses three coins.
Exercise
Change lcs_traceback so that it returns the index pairs (i, j) in a and b where matched characters occur, instead of the string. What are the pairs for "ABC" and "ACB" with prefer_up=True?
Show answer
In the match branch, append (i - 1, j - 1) instead of a[i - 1], and return list(reversed(out)). For "ABC" and "ACB" with prefer_up=True, the result is [(0, 0), (1, 2)]: 'A' at index 0 of both strings, and 'B' at index 1 of a and index 2 of b.
Exercise
You have a dp list for coin change but kept no choice table, and you call coins_from_table with coins [2] and amount 3 after deleting its first guard line. What happens, and which property of floating-point infinity causes it?
Show answer
The loop never ends. dp[3] and dp[1] are both infinite, and inf + 1 == inf is True, so coin 2 "matches" at amount 3 and the walk moves to amount 1. At amount 1 no coin fits, so break never runs and a never changes, and the while a > 0 loop spins forever. The guard if dp[amount] == float('inf'): return [] prevents this.