Notes
All notes

Dynamic Programming (DSA #26)

Naive recursive Fibonacci on 40 takes seconds; on 50, minutes; on 100, longer than the universe has existed. It recomputes fib(38) billions of times. Yet the whole problem has only 100 distinct answers. Dynamic programming is the observation that if subproblems repeat, you should solve each once and remember the result. That single idea turns exponential algorithms into polynomial ones and is the most common “hard interview” topic.

This chapter covers the two properties DP needs, the two implementation styles, the standard 1D and 2D problems, and how to optimise space.

When DP applies

Two conditions:

If subproblems do not overlap, it is divide and conquer (Chapter 24). If a local greedy rule is provably optimal, greedy is simpler (Chapter 25). DP is the tool when neither holds.

Two styles: memoisation and tabulation

Top-down memoisation keeps the recursion and caches results. It is the easier translation from a brute-force recurrence.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

The lru_cache turns the exponential recursion tree into a linear chain of \(n\) distinct calls.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.5cm, inner sep=0pt, font=\scriptsize}]
  \node[n, fill=orange!28] (r) at (0,0) {5};
  \node[n] (a) at (-1.4,-0.8) {4}; \node[n] (b) at (1.4,-0.8) {3};
  \node[n] (c) at (-2.0,-1.6) {3}; \node[n, fill=green!25] (d) at (-0.8,-1.6) {2};
  \node[n, fill=green!25] (e) at (0.8,-1.6) {2}; \node[n] (f) at (2.0,-1.6) {1};
  \draw[->, thick] (r) -- (a); \draw[->, thick] (r) -- (b);
  \draw[->, thick] (a) -- (c); \draw[->, thick] (a) -- (d);
  \draw[->, thick] (b) -- (e); \draw[->, thick] (b) -- (f);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.1) {green repeats: cache it once and reuse};
\end{tikzpicture}

Bottom-up tabulation fills a table iteratively, from the base cases up. It avoids recursion overhead and often allows space optimisation.

def fib(n):
    if n < 2: return n
    a, b = 0, 1
    for _ in range(n - 1):
        a, b = b, a + b        # only two values needed
    return b

Both give the same answer; the bottom-up version here is \(O(n)\) time and \(O(1)\) space.

A method for any DP problem

  1. Define the state — what the subproblem is, e.g. dp[i] = answer for the first i items.
  2. Write the recurrence — how dp[i] follows from smaller states.
  3. Set base cases — the answers you know directly.
  4. Decide the order — dependencies must be filled first.
  5. Optimise space if the full table is not needed.

The hardest step is (1): getting the state right makes the rest mechanical.

1D DP

Climbing stairs. Each step you climb 1 or 2 stairs; count the ways. This is Fibonacci in disguise.

\[ dp[i] = dp[i-1] + dp[i-2], \qquad dp[0] = dp[1] = 1 \]

def climb(n):
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a

House robber. No two adjacent houses may be robbed; maximise the take.

\[ dp[i] = \max(dp[i-1],\ dp[i-2] + \text{nums}[i]) \]

def rob(nums):
    prev, curr = 0, 0
    for x in nums:
        prev, curr = curr, max(curr, prev + x)
    return curr

Each state only needs the previous two, so a couple of variables replace an \(n\)-length table.

2D DP: grid paths

Count paths from the top-left to the bottom-right moving only right or down. This is the companion note Unique Paths.

\[ dp[i][j] = dp[i-1][j] + dp[i][j-1] \]

def unique_paths(m, n):
    dp = [1] * n                    # first row
    for i in range(1, m):
        for j in range(1, n):
            dp[j] += dp[j - 1]      # dp[j] (above) + dp[j-1] (left)
    return dp[-1]

The rolling 1D array works because each cell depends only on the cell above (the old dp[j]) and the cell to the left (the new dp[j-1]).

2D DP: longest common subsequence

Given two strings, find the length of the longest subsequence in both. This is the basis of diff.

\[ dp[i][j] = \begin{cases} dp[i-1][j-1] + 1 & \text{if } a[i-1] = b[j-1] \\ \max(dp[i-1][j],\ dp[i][j-1]) & \text{otherwise} \end{cases} \]

def lcs(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 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[len(a)][len(b)]

Edit distance (Levenshtein) is the same table with three operations and is the engine behind spell-check and fuzzy matching.

0/1 knapsack

Choose a subset of items to maximise value within a weight limit. Greedy fails (Chapter 25); DP is exact.

\[ dp[w] = \max(dp[w],\ dp[w - \text{weight}[i]] + \text{value}[i]) \]

def knapsack(items, capacity):
    dp = [0] * (capacity + 1)
    for weight, value in items:
        for w in range(capacity, weight - 1, -1):   # iterate DOWN
            dp[w] = max(dp[w], dp[w - weight] + value)
    return dp[capacity]

The downward loop is essential: it ensures each item is used at most once. Iterating upward would allow reusing an item (which is the unbounded knapsack variant).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.62cm, minimum height=0.55cm, font=\scriptsize}]
  \foreach \w in {0,...,6} { \node[c, fill=blue!8] at (\w*0.68,0) {\w}; }
  \node[font=\scriptsize, anchor=east] at (-0.4,0) {w:};
  \foreach \w/\val in {0/0,1/0,2/0,3/0,4/0,5/0,6/0} { }
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.0,-0.6) {one row, updated right-to-left to avoid item reuse};
\end{tikzpicture}

Space optimisation

Most DP tables can be reduced when each state depends on a few neighbours:

The trade is always the same: you keep time complexity and shrink memory, at the cost of a more delicate loop order.

Pitfalls

QQuestionSelf-check

What two properties must a problem have for DP? What is the difference between memoisation and tabulation, and why does knapsack iterate the weight loop downward?

ASolution

Overlapping subproblems and optimal substructure. Memoisation is top-down recursion with a cache; tabulation is bottom-up table filling. The weight loop runs downward so each item contributes at most once: dp[w] reads dp[w-weight] from the previous item’s state, not the current one, preventing item reuse.

Next: Two Pointers and Sliding Window (DSA #27) — linear passes over arrays and strings.