PDSA Interactive Book
Week 9

Dynamic Programming

Remember what you've already solved — the idea that turns exponential recursions into polynomial tables.

After this chapter you can…
  • turn an inductive definition into a memoised or bottom-up solution
  • fill LCS, common-subword, edit-distance and grid-path tables by hand
  • state the cost of a DP as (#subproblems × work per subproblem)
  • explain the matrix-chain and knapsack recurrences

The problem with plain recursion

Fibonacci numbers are defined inductively: F(0) = 0, F(1) = 1, F(n) = F(n−1) + F(n−2). Translating that definition straight into code is natural — and terrible.

Python · editable
Expected output: 6765 using 21891 calls fib(25) used 242785 calls
Call tree of fib(n) — count how many times each value is recomputedInteractive

fib(n) calls fib(n−2) once directly and again inside fib(n−1). The same subproblems are solved over and over, so the number of calls grows like 1.618ⁿ. But there are only n + 1 distinct subproblems! If we remember each answer after computing it, the work collapses to O(n).

Memoisation (top-down)

Keep a table (dictionary). Before computing fib(k), look it up; after computing, store it. The recursion is unchanged, but each value is computed once.

Dynamic programming (bottom-up)

Skip recursion: fill the table in an order where every dependency is already computed — here 0, 1, 2, …, n. Often only the last few entries are needed, so memory can drop too.

Python · editable
Expected output: 2880067194370816120 2880067194370816120 memo calls: 91
Dynamic programming recipe
  1. Find an inductive definition of the answer in terms of smaller subproblems.
  2. Notice that subproblems overlap (the same ones are needed many times).
  3. Pick an order in which dependencies are computed first — or memoise the recursion.
  4. Read the answer from the table. Cost = (number of subproblems) × (work per subproblem).
Check yourself

Why is naive recursive Fibonacci exponential but memoised Fibonacci linear?

Predict the output

What does this print?

memo = {}
def f(n):
    if n in memo:
        return memo[n]
    memo[n] = n if n < 2 else f(n - 1) + f(n - 2)
    return memo[n]
f(6)
print(len(memo), memo[6])

Counting paths on a grid

A robot moves on an R × C grid, one step right or down. Some cells are blocked. How many different routes lead from the top-left to the bottom-right?

Inductive definition. Let paths(i, j) be the number of routes to cell (i, j). A route must arrive from the cell above or the cell to the left, so paths(i, j) = paths(i−1, j) + paths(i, j−1) — or 0 if (i, j) is blocked. Fill the table row by row.

Python · editable
Expected output: [1, 1, 1, 1] [1, 0, 1, 2] [1, 1, 2, 0] [1, 2, 4, 4] routes: 4
Grid paths — click cells to block them and watch the table changeInteractive

Time and space are both O(R·C): one table entry, each computed with O(1) work.

Predict the output

Number of right/down routes in an open 3×3 grid?

R, C = 3, 3
P = [[1] * C for _ in range(R)]
for i in range(1, R):
    for j in range(1, C):
        P[i][j] = P[i - 1][j] + P[i][j - 1]
print(P[-1][-1])
Check yourself

In grid-path counting, which order fills the table so every dependency is ready?

Longest common subsequence (LCS)

A subsequence keeps letters in order but may skip some: "sct" is a subsequence of "secret". Given two strings, find the length of their longest common subsequence — used in diff tools, DNA comparison and plagiarism checks.

Inductive definition. Let L(i, j) be the LCS length of the suffixes a[i:] and b[j:]. If a[i] == b[j], we can match them: L(i, j) = 1 + L(i+1, j+1). Otherwise one of them is unmatched: L(i, j) = max(L(i+1, j), L(i, j+1)). The base case is an empty suffix: 0.

Python · editable
Expected output: (4, 'sect') (4, 'GTAB')
LCS table — type two strings and trace the recovered subsequenceInteractive
Cost

(m+1)(n+1) cells, each O(1) ⇒ O(mn) time and space. The naive recursion explores 2^(m+n) paths.

Longest common substring (contiguous)

If the matched letters must be consecutive (a common subword), the recurrence changes: LCW(i, j) = 1 + LCW(i+1, j+1) if a[i] == b[j], otherwise 0 (the run is broken). The answer is the maximum entry in the table, not the corner.

Longest common subword — runs along diagonalsInteractive
Predict the output

What does this print? (type the exact output)

def lcs(a, b):
    m, n = len(a), len(b)
    L = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            L[i][j] = 1 + L[i + 1][j + 1] if a[i] == b[j] else max(L[i + 1][j], L[i][j + 1])
    return L[0][0]
print(lcs("ABCBDAB", "BDCABA"))
Check yourself

a = 'abc', b = 'acb'. What is the LCS length?

Edit distance

How many single-character edits turn one word into another? Allowed edits: insert a letter, delete a letter, substitute one letter. ED("bisect", "secret") is the minimum number of operations — the idea behind spell-checkers and DNA alignment.

Inductive definition. Let E(i, j) be the distance between the suffixes a[i:] and b[j:]. If one is empty, we must insert or delete the rest: E(m, j) = n − j and E(i, n) = m − i. Otherwise: - if a[i] == b[j], no edit is needed: E(i, j) = E(i+1, j+1); - else take 1 + min(E(i+1, j) [delete], E(i, j+1) [insert], E(i+1, j+1) [substitute]).

Python · editable
Expected output: 4 3 3
Edit distance tableInteractive
Predict the output

What does this print?

def ed(a, b):
    m, n = len(a), len(b)
    E = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1): E[i][n] = m - i
    for j in range(n + 1): E[m][j] = n - j
    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            E[i][j] = E[i+1][j+1] if a[i] == b[j] else 1 + min(E[i+1][j], E[i][j+1], E[i+1][j+1])
    return E[0][0]
print(ed("cat", "cut"), ed("cat", "cart"), ed("abc", "xyz"))
Check yourself

For strings of lengths m and n, the edit-distance table has how many cells?

Matrix chain multiplication

Multiplying a p×q matrix by a q×r matrix costs p·q·r scalar multiplications. Matrix multiplication is associative, so (AB)C and A(BC) give the same product — but the costs can differ wildly. Given a chain M₁M₂…Mₙ, find the cheapest way to parenthesise it.

Example

A is 10×100, B is 100×5, C is 5×50. (AB)C costs 10·100·5 + 10·5·50 = 5000 + 2500 = 7500. A(BC) costs 100·5·50 + 10·100·50 = 25000 + 50000 = 75000. Ten times worse!

Inductive definition. Let C(i, j) be the cheapest cost of multiplying Mᵢ … Mⱼ. Choose where to make the last split k, with i ≤ k < j: the cost is the left part + the right part + the final multiplication of the two results:

C(i, j) = min over k of [ C(i, k) + C(k+1, j) + rᵢ · c_k · c_j ],   C(i, i) = 0

Here matrix Mᵢ has dimensions rᵢ × cᵢ. We fill the table in order of increasing chain length: all intervals of length 2, then 3, and so on. There are O(n²) subproblems with O(n) choices each: O(n³) time.

Python · editable
Expected output: (7500, '((M1M2)M3)') (1344, '((M1M2)((M3M4)M5))')
Matrix chain — enter dimensions and read the optimal parenthesisationInteractive
Check yourself

Why can't we just always multiply left to right?

Check yourself

A is 2×3, B is 3×4. How many scalar multiplications does AB take?

Choices with a budget: 0/1 knapsack

You have a bag that holds weight W and items with weights and values. Take each item or leave it; maximise total value. Greedy by value-per-weight fails here, but DP works. Let K(i, w) be the best value using the first i items with capacity w:

K(i, w) = max( K(i−1, w),   v_i + K(i−1, w − w_i) )   (second option only if w_i ≤ w)

Python · editable
Expected output: 9
0/1 knapsack — fill the table cell by cellInteractive
Pseudo-polynomial

The table has n × W cells. That is fast if W is small, but W is a number, and its input size is only log W bits — so the running time is exponential in the size of the input. Knapsack is NP-hard.

Coin change — DP table versus greedyInteractive
Predict the output

Minimum number of coins {1, 3, 4} to make 6?

coins = [1, 3, 4]
best = [0] + [float("inf")] * 6
for amount in range(1, 7):
    for c in coins:
        if c <= amount:
            best[amount] = min(best[amount], best[amount - c] + 1)
print(best[6])

Chapter challenge — Week 9

…
Check yourself

The two requirements for dynamic programming to help are…

Predict the output

What does this print? (type the exact output)

def paths(r, c):
    P = [[1] * c for _ in range(r)]
    for i in range(1, r):
        for j in range(1, c):
            P[i][j] = P[i-1][j] + P[i][j-1]
    return P[-1][-1]
print(paths(4, 4))
Check yourself

Filling the LCS table for strings of length 300 and 400 takes about…

Put in order

Designing a DP solution.

Check yourself

What is the edit distance between 'ab' and 'ba'?

Predict the output

What does this print? (type the exact output)

a, b = "abcd", "acbd"
m, n = len(a), len(b)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
    for j in range(n - 1, -1, -1):
        L[i][j] = 1 + L[i+1][j+1] if a[i] == b[j] else max(L[i+1][j], L[i][j+1])
print(L[0][0])
Check yourself

Which statements about DP are true?

Check yourself

Why does greedy fail for coin change with coins {1, 3, 4} and amount 6?

Practice on LeetCode

Dynamic programming: sequences, grids, knapsack, strings and intervals.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 15 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Fibonacci Number ↗Easymemoise or fill a table
Climbing Stairs ↗Easythe same recurrence
House Robber ↗Mediumchoose-or-skip DP
Unique Paths ↗Mediumgrid paths
Unique Paths II ↗Mediumgrid paths with blocked cells
Minimum Path Sum ↗Mediumgrid DP with min
Coin Change ↗Mediumwhere greedy fails and DP works
Partition Equal Subset Sum ↗Medium0/1 knapsack
Target Sum ↗Mediumsubset-sum style DP
Longest Increasing Subsequence ↗MediumO(n²) DP, then the O(n log n) idea
Longest Common Subsequence ↗Mediumthe LCS table from this chapter
Maximum Length of Repeated Subarray ↗Mediumlongest common subword (diagonal runs)
Edit Distance ↗Mediumthe edit-distance table
Delete Operation for Two Strings ↗MediumLCS in disguise
Burst Balloons ↗Hardinterval DP, like matrix-chain

Key takeaways

  • Naive recursion re-solves the same subproblems; DP solves each once and stores the answers — top-down (memoisation) or bottom-up (table).
  • The recipe: inductive definition → overlapping subproblems → fill order → read the answer. Cost = number of subproblems × work each.
  • LCS / longest common subword / edit distance fill an m×n table in O(mn).
  • Matrix chain: O(n²) subproblems with O(n) splits each ⇒ O(n³). Knapsack: O(nW), pseudo-polynomial.
  • Where greedy fails (arbitrary coin change), DP still finds the optimum.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.