Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 12: Dynamic Programming — Tabulation and Classic Problems

Memoisation is the top-down way to do dynamic programming: start from the answer you want and recurse downward, remembering results. Tabulation is the bottom-up way: build a table of answers starting from the smallest subproblems and working upward, until the table holds the answer you want. The two approaches solve the same problems in the same time; tabulation avoids recursion entirely, which means no recursion limit and often less memory, since you can sometimes keep only the last few table entries instead of the whole table.

The Fibonacci table is the simplest example: fill in table[0] = 0 and table[1] = 1, then compute each later entry as the sum of the two before it. The same idea scales to the classic DP problems. In the coin change problem, you have coins of given values and must make a target amount with as few coins as possible; the table entry for each amount is one plus the best entry for the amount minus one coin, minimised over all coins. In the 0/1 knapsack, each item can be taken or left, and the table tracks the best value achievable with each capacity. Different stories, same shape: a table, a recurrence, and a base case.

def fib_table(n):
    if n < 2:
        return n
    table = [0] * (n + 1)
    table[1] = 1
    for i in range(2, n + 1):
        table[i] = table[i - 1] + table[i - 2]
    return table[n]


def coin_change(coins, amount):
    INF = float("inf")
    table = [INF] * (amount + 1)
    table[0] = 0
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                table[a] = min(table[a], table[a - c] + 1)
    return -1 if table[amount] == INF else table[amount]


print(fib_table(10))            # 55
print(coin_change([1, 5, 10], 12))  # 3 — 10 + 1 + 1

A recipe for DP problems

Most DP problems yield to the same five-step recipe. First, define the state: what inputs identify one subproblem — for coin change, the amount remaining. Second, write the recurrence: how the answer for a state follows from smaller states. Third, set the base cases: the states whose answers are obvious. Fourth, decide the order: which states must be computed before which — bottom-up tables usually fill in increasing order. Fifth, read off the answer: which table entry is the one the problem asked for? Practising this recipe on the classics — Fibonacci, coin change, knapsack, longest common subsequence, grid paths — builds the pattern recognition that makes new DP problems feel familiar.

One warning: DP tables can be large. A table of size n is fine; a table of size n by m is fine for moderate inputs; but a table indexed by every possible sum or every subset grows fast, and that growth is the real constraint on many DP solutions. When a table is too big, the fix is often to notice that each row only depends on the previous row, and keep two rows instead of the whole table. Space optimisation like that is an advanced skill — for now, get the table right first, and optimise only when the limits demand it.

Going further

Tabulation tables can often be shrunk. In the Fibonacci table, each entry depends only on the two before it, so you can keep two variables instead of a whole list — the table collapses to O(1) space. In the coin change table, each entry depends on earlier entries in the same row, so the full table is needed in the simple version, but many two-dimensional DP tables only need the previous row: a grid path table, for example, can be computed row by row, keeping just the current row and the one above it. Space optimisation is an advanced skill, but the idea is simple — ask which earlier entries each new entry actually reads, and keep only those.

The longest common subsequence (LCS) is the classic two-dimensional DP problem, and it is worth knowing its shape even before you implement it. Given two strings, the table entry for the first i characters of one and the first j of the other is the length of their longest common subsequence. If the two characters match, the answer is one plus the diagonal entry; if they do not, it is the larger of the entry above and the entry to the left. That is the whole recurrence, and it is the same idea as edit distance — the number of changes needed to turn one string into another — which powers spell checkers and file comparison tools.

To practise the five-step recipe, apply it to a problem you have not seen solved: the number of ways to climb a staircase of n steps when you may take one or two steps at a time. The state is the step you are on; the recurrence is that the ways to reach step i equal the ways to reach i - 1 plus the ways to reach i - 2; the base cases are one way to be on step 0 and one way to reach step 1; the table fills in increasing order; and the answer is the entry for step n. If the recurrence looks familiar, it should: it is the Fibonacci sequence in disguise, which is a useful reminder that different problems often share the same structure.

Watch & Learn

One video to watch for this unit, from a trusted educator.

Key Terms

Tabulation
Bottom-up dynamic programming: filling a table from the smallest subproblems upward.
DP table
The array (or grid) that stores the answer to every subproblem, indexed by state.
Recurrence (DP)
The rule expressing a table entry in terms of smaller entries, such as table[i] = table[i-1] + table[i-2].
Coin change
The classic DP problem of making an amount with the fewest coins (or counting the ways).
0/1 knapsack
The classic DP problem of choosing items to maximise value within a capacity, each item taken at most once.
Longest common subsequence
The classic DP problem of the longest sequence appearing as a subsequence in two strings.
Base case (DP)
The table entries whose answers are known directly, such as table[0] = 0 for coin change.

Discussion Questions

  1. When would you choose tabulation over memoisation, and when the other way round? Think about recursion limits and about subproblems you never need.
  2. In coin change, why is table[0] = 0 the right base case? What would happen if it were infinity instead?
  3. Why is the five-step recipe useful even when you already suspect the answer? What does writing the recurrence force you to decide?

Practice Questions

  1. What is the difference between memoisation and tabulation?
  2. Trace fib_table(4). What is table[2], table[3] and table[4]?
  3. In coin change, what does table[a] = min(table[a], table[a - c] + 1) mean in words?
  4. Why does coin_change return -1 when the table entry is still infinity?
  5. How many coins does coin_change([1, 5, 10], 12) use, and which coins?
Show answers
  1. Memoisation is top-down recursion with a cache; tabulation is bottom-up table filling. Both solve each subproblem once; tabulation avoids recursion and its limits.
  2. table[2] = 1, table[3] = 2, table[4] = 3. Each entry is the sum of the two before it, starting from table[0] = 0 and table[1] = 1.
  3. Using one coin of value c, plus the best way to make a - c, is a candidate for the best way to make a. Taking the minimum over all coins gives the fewest coins for amount a.
  4. Because the amount cannot be made with the given coins. Infinity means no combination of coins reached that amount.
  5. 3 coins: 10 + 1 + 1. The table finds the minimum; 10 + 1 + 1 uses three coins, while twelve 1-coins would use twelve.
Keep reading to complete this lesson