Bitpath

Dynamic Programming

Dynamic programming is recursion that refuses to repeat itself. Learn to define a state, write its recurrence, and fill a memo or a table, then use that on stairs, robbers, coins, grids, edit distance, knapsacks and word breaks.

  • Advanced
  • 4 units, 12 lessons, 146 exercises
  • Python, JavaScript or TypeScript
  • Builds on Recursion & Backtracking

Unit 01 · 3 lessons

Top-down: recursion plus memory

Turn a slow recursion into a fast one by remembering answers

  1. > start01Overlapping subproblems
  2. 02Define the state
  3. BOSSMin cost climbing stairs
Unit prize
  1. 01
    Overlapping subproblems

    Why naive recursion repeats itself, and how a memo stops it

  2. 02
    Define the state

    Climbing stairs: state, recurrence, base cases

  3. BOSS
    Min cost climbing stairs

    Choices combined with min, solved end to end

Read the unit guide

Dynamic programming starts with a recursion that keeps asking the same question. Naive fib(5) computes fib(2) three times, and each repeat redoes a whole subtree of calls. That is what "overlapping subproblems" means, and it is why the naive version takes exponential time.

The fix is a memo: a map from input to answer. Every call does three things in order. Check the memo and return if the answer is there. Otherwise compute it from smaller calls. Store it before returning. Each distinct input is now computed once, so the cost is the number of distinct inputs times the work per input.

To design a solution, write down three things. The state: what a call means, in words ("ways(n) is the number of ways to reach stair n"). The recurrence: how a state is built from smaller states, found by asking what the last move could have been. The base cases: the states small enough to answer without recursing.

When the problem asks for a best value, the recurrence combines the choices with min or max instead of adding them. Min cost climbing stairs is the model: pay(i) = cost[i] + min(pay(i + 1), pay(i + 2)).

The classic pitfalls: a base case that is off by one (so the recursion reads past the end), storing after returning (so nothing is ever stored), and a state that leaves out something the answer depends on. If two calls with the same arguments could need different answers, the state is too small.

Unit 02 · 3 lessons

Bottom-up: fill a table

Replace the recursion with a loop that fills a table in dependency order

  1. 01From memo to table
  2. 02House robber
  3. BOSSCoin change
Unit prize
  1. 01
    From memo to table

    A dp array filled smallest first, then two rolling variables

  2. 02
    House robber

    Take it or skip it: a choice at every cell

  3. BOSS
    Coin change

    Fewest coins with an infinity sentinel, then counting ways

Read the unit guide

A memoized recursion dives to the base cases and then fills its memo from the smallest input upward. Tabulation does the same work without the dive: make an array dp, write the base cases in, and loop so that every cell is computed after the cells it reads.

Say what a cell means before you write the loop. For stairs, dp[i] is the number of ways to reach stair i. For the house robber, dp[i] is the most money from the first i houses, and each house is a choice: skip it (dp[i - 1]) or take it (dp[i - 2] plus its money).

Loop direction is not a matter of taste. If dp[i] reads dp[i - 1] and dp[i - 2], i must go upward. Loop the wrong way and you read cells that still hold their initial values, and the code runs happily and returns nonsense.

When a cell reads only the last one or two cells, the array is optional. Two rolling variables do the job in O(1) space. Update them together, or save the old value first: overwriting one before you use it is the standard bug.

Coin change adds two ideas. For "fewest coins", start every cell at infinity, meaning "no way found yet", so any real answer wins a min and anything still infinite at the end is impossible. For "how many ways", put the coins in the outer loop to count combinations; with amounts in the outer loop, 1+2 and 2+1 are counted separately.

Greedy shortcuts fail on these problems. Grabbing the richest house or the biggest coin commits you before you can see what it rules out. The table tries every choice and keeps the best.

Unit 03 · 3 lessons

Two dimensions: grids and strings

Fill a 2D table where each cell reads its neighbours above and to the left

  1. 01Grid paths
  2. 02Longest common subsequence
  3. BOSSEdit distance
Unit prize
  1. 01
    Grid paths

    Count routes cell by cell, with walls and a rolling row

  2. 02
    Longest common subsequence

    Compare two strings prefix by prefix in a table

  3. BOSS
    Edit distance

    Insert, delete or replace: three neighbours, one min

Read the unit guide

Some states need two numbers. A position in a grid is a row and a column. A comparison of two strings is a prefix of one and a prefix of the other. The table becomes a rectangle, and dp[r][c] answers the question for that pair.

The method does not change. Say what a cell means, write the base cases along the top row and left column, and fill the rest row by row so every cell is computed after the neighbours it reads.

For grid routes, a cell is reached from above or from the left, so its count is the sum of those two. Walls are cells with zero routes. Swap the sum for a min and the same table finds the cheapest route instead of counting them.

For two strings, cell (i, j) compares the first i letters of one with the first j letters of the other. In the longest common subsequence, matching last letters extend the diagonal cell by 1; otherwise you drop a letter from one string and keep the better of above and left. Edit distance uses the same three neighbours as replace, delete and insert.

Two practical traps. Build the table with a fresh list per row: [[0] * 3] * 2 in Python and Array(2).fill([0, 0, 0]) in JavaScript both make every row the same object. And remember the extra row and column for the empty prefix, which is why these tables have one more row and column than the strings have letters.

When a cell reads only the current row and the one above, you can keep one or two rows instead of the whole table. Time stays O(rows × cols); memory drops to O(cols).

Unit 04 · 3 lessons

Classic patterns

Recognise knapsack, subsequence and partition problems, and know when DP is the right tool

  1. 010/1 knapsack
  2. 02Longest increasing subsequence
  3. BOSSSpot the DP
Unit prize
  1. 01
    0/1 knapsack

    Take or skip each item under a weight limit

  2. 02
    Longest increasing subsequence

    An O(n²) table, then the O(n log n) idea

  3. BOSS
    Spot the DP

    Word break, and telling DP problems from greedy ones

Read the unit guide

Most DP problems you meet are a known pattern in new clothes. Learn the handful of classic shapes and the rest is spotting which one you are looking at.

Knapsack: items with a weight and a value, a capacity, and a take-or-skip choice per item. The state is the item you are deciding on plus the capacity left. In the one-row table, loop the capacity downward when each item may be used once, and upward when items can repeat. Coin change is the repeating kind.

Longest increasing subsequence: dp[i] is the best length that ends exactly at index i, built from every earlier index with a smaller value. The answer is the largest cell, not the last one. That table is O(n²); keeping a sorted list of smallest tails and using binary search brings it down to O(n log n).

Partition problems cut a sequence into pieces. For word break, ok[i] says whether the first i characters can be cut into allowed words, and it is true when some earlier cut point j is good and the piece from j to i is a word.

How do you know DP fits? Three checks. The answer can be built from answers to smaller versions of the same question. Those smaller questions repeat. And a locally best choice can be wrong, so greedy is not safe.

If no choice ever needs revisiting, as with coins of 1, 5, 10 and 25, greedy is simpler and faster. If subproblems never repeat, plain recursion is enough. DP earns its place only when you have both overlap and a real choice.

Learn Dynamic Programming on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy