Skip to content

Software interviews

Dynamic programming for coding interviews: a method and worked problems

Dynamic programming solves a problem by solving smaller versions of it once each and reusing the answers. It looks hard because the recurrence is not obvious, but a fixed set of five questions finds it: what is a state, what are the choices, what are the base cases, in what order do you fill them and where is the answer. This page gives that method, shows the cost of not reusing answers, works three patterns and gives four original problems with answers a separate program recomputes.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What dynamic programming is, and the five questions that find the answer

Dynamic programming is recursion that remembers. A recursive rule defines the answer for a case from the answers for smaller cases. When different branches of the recursion ask for the same small case, you compute it once, store it and reuse it. The MIT OpenCourseWare course 6.006 Introduction to Algorithms spends four lectures on it. The titles of three of them name standard examples: Fibonacci numbers and paths in a directed acyclic graph, longest common subsequence, longest increasing subsequence and coin problems, rod cutting and subset sums.

Here is a five-question routine in our own words that you can say aloud in an interview.

  1. State. What do the small cases look like? Name the parameters that define one, such as the first i items, or a capacity c.
  2. Choices. At a state, what can you do next, and how does each choice reduce to a smaller state?
  3. Base cases. Which smallest states have an answer you can write down, such as zero items or zero capacity?
  4. Order. In what order can you fill the states so that each is ready when needed? Smaller first.
  5. Answer. Which state holds the answer to the original problem?

The cost follows from the states. The work is the number of states times the work to evaluate one. A table of n states with two choices each costs O(n), and a table of m by n states costs O(mn). Say both numbers, and the space, which can often be cut to the last row or the last two entries.

What reusing answers saves

The Python documentation for functools shows the idea in a few lines. The decorator cache is a simple lightweight unbounded function cache, sometimes called memoize, that wraps the function in a dictionary lookup on its arguments. For lru_cache with no size limit, the page works Fibonacci numbers as its example, calling the function for n from 0 to 15, and reports 16 misses and 28 hits: each of the 16 distinct values was computed once and every other request was a lookup. The arguments to a cached function must be hashable, because a dictionary stores the results.

Without the cache, the recursive Fibonacci rule recomputes the same values over and over. Our count: the number of calls C(n) satisfies C(n) = C(n - 1) + C(n - 2) + 1, with C(0) = C(1) = 1, and this equals 2 x F(n + 1) - 1 where F is the Fibonacci sequence.

Calls made by the plain recursive Fibonacci rule against the distinct values a cache computes, from our own count
nCalls without a cacheDistinct values computed with one
1017711
2021,89121
302,692,53731
40331,160,28141

The table is the whole argument for the technique. The plain rule makes about 1.6 times as many calls for each step up in n, while the cached version adds one new value. Counting the states and saying "each is computed once" is the sentence an interviewer wants to hear.

The problem signals that call for dynamic programming

The wording usually gives it away. Look for a request for a best value, a count of ways, or a yes or no on possibility, over choices that overlap.

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
"Largest total with no two neighbors"Take or skip, with a link to the previous itemOne-dimensional table over the items
"How many ways to make a total"Counting ordered or unordered combinationsTable over totals, coins on the outside loop
"Longest common subsequence of two texts"Two sequences, alignedTwo-dimensional table over prefixes
"Best value within a weight limit"Each item used once, a limit sharedTable over capacity, filled downward
"Fewest coins" or "shortest way"The best of several smaller answers plus oneTable over amounts
"Is it possible to reach"Yes or no built from smaller yes or no answersTable of true and false

Pattern 1: take or skip, in one dimension

Problem 1 gives ten houses in a row with amounts, and you may not take from neighbors. State: best(i) is the largest total using the first i houses. Choices: skip house i, which gives best(i - 1), or take it, which gives its amount plus best(i - 2). Base cases: best(0) is 0 and best(1) is the first amount. Order: smaller i first. Answer: best(10). The table fills in one pass, and only the last two entries are ever needed, so the space is O(1). The same take or skip shape answers many questions; only the link to earlier items changes.

Pattern 2: count the ways, and mind the loop order

Problem 2 counts the ways to make 60 from coins of 1, 5, 10 and 25. State: ways(t) is the number of ways to make the total t. Add one coin type at a time, and for each coin value c, update ways(t) to ways(t) plus ways(t - c), going up through t. Putting the coins on the outside loop counts each combination once. If you put the totals on the outside and the coins inside, you count different orders of the same coins as different ways, which is a different problem, so know which one the statement describes. A useful check is to compute the answer a second way, here by splitting on the number of 25-coins, as the worked steps do.

Pattern 3: a table over two inputs

When the problem has two sequences, or one sequence and a limit, the state has two parameters. Problem 3 is the longest common subsequence of two short texts. State: L(i, j) is the answer for the first i characters of one text and the first j of the other. If the two last characters match, L(i, j) is L(i - 1, j - 1) plus 1. Otherwise it is the larger of L(i - 1, j) and L(i, j - 1). The table has one cell per pair, so the cost is O(mn). Problem 4 is the knapsack: choose items, each at most once, to maximize value within a weight limit. State: best(c) for each capacity. For each item, update the capacities from the top down, so that an item is not used twice within one update. Filling the capacities upward instead lets one item be used again and again, which is a different problem.

Two tests, and the question shapes that pass them

Two properties mark a problem that dynamic programming fits. The best answer to the whole must be assembled from best answers to smaller pieces, and the same smaller pieces must come up again from different branches. If only the first holds, a single greedy choice or a plain recursion may do. If only the second holds, a cache alone may be enough. Checking both before you write anything is faster than discovering the gap halfway through a table.

Interview questions repeat a small set of shapes, and the wording changes more than the structure. Learn the shape and you can write the state in your own words. The table lists five shapes with the state and the rule that fills it.

Five question shapes, the state and the rule
ShapeA way the question is wordedStateRule that fills it
Fewest items for a totalThe fewest coins that make an amountfewest(a) for each amount aOne more than the best fewest(a - c) over each coin c that fits
Count the ways to climbIn how many ways can you reach step n using one or two steps at a timeways(n) for each step nways(n - 1) plus ways(n - 2)
Edit distance between two textsThe fewest changes that turn one word into anothercost(i, j) for the first i and j charactersThe cheapest of an insert, a delete or a replace, or a free match
A region in a gridThe largest square of ones in a binary gridside(r, c) for the square ending at that cellOne more than the smallest of the three neighbors above and to the left, if the cell is a one
Match a patternWhether a text fits a pattern with wildcardsfits(i, j) for the first i characters and j pattern symbolsA case for each symbol kind, using earlier cells

Two of these shapes fit a short table you can fill by hand. With coins of 1, 2, 5, the fewest coins that make each amount from 0 to 11 follow from the rule in the first row. The table below is filled by code from that rule.

Fewest coins for each amount, with coins of 1, 2 and 5 (filled by code)
AmountFewest coinsOne way to make it
00No coins
111 coin, one more than the best of the smaller amounts
211 coin, one more than the best of the smaller amounts
322 coins, one more than the best of the smaller amounts
422 coins, one more than the best of the smaller amounts
511 coin, one more than the best of the smaller amounts
622 coins, one more than the best of the smaller amounts
722 coins, one more than the best of the smaller amounts
833 coins, one more than the best of the smaller amounts
933 coins, one more than the best of the smaller amounts
1022 coins, one more than the best of the smaller amounts
1133 coins, one more than the best of the smaller amounts

For the staircase shape, the count for n steps follows ways(n) = ways(n - 1) + ways(n - 2) with one way for zero or one step. For 1 to 8 steps the counts are 1, 2, 3, 5, 8, 13, 21, 34, so eight steps can be climbed in 34 ways. Each number is the sum of the two before it, which is why a hand table is quick to check.

Say the state aloud before the rule, and the rule before the code. An interviewer who hears a clear state can correct a mistake early, while one who hears only code has to read it first.

Edge cases interviewers probe

  • Empty inputs and zero targets. The base cases are where many solutions fail, so say what the table holds at index 0.
  • Off by one in the table size. A table for n items needs n + 1 rows when row 0 stands for no items.
  • Order of the loops, as in the coin counting and the knapsack. State which direction you loop and why.
  • Impossible targets. If no combination makes the total, decide whether you return 0, a large number or an error, and make sure the large number cannot overflow when you add 1 to it.
  • Recursion depth. A top-down solution recurses as deep as the problem is large, so mention that a bottom-up table avoids that.
  • Space. Name what you can drop: the last row, or all but the last two entries.

A good habit is to fill the table by hand for the smallest input that has a choice in it before you call the code done.

Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from take or skip, through counting ways, to a two-dimensional table and a capacity table.

Problem 1. Ten houses in a row hold the amounts 6, 7, 1, 3, 8, 2, 4, 9, 5, 3. You may take from any houses, but never from two houses that are next to each other. What is the largest total you can take? Give an integer.

Show the answer and the working

Answer: 27

  1. Let best(i) be the largest total using only the first i houses. For house i, either skip it, which gives best(i - 1), or take it, which gives its amount plus best(i - 2). So best(i) = the larger of those two. Base: best(0) = 0 and best(1) = 6.
  2. Filling in order for i = 1 to 10: 6, 7, 7, 10, 15, 15, 19, 24, 24, 27.
  3. The answer is best(10) = 27, for example the houses with 7, 8, 9 and 3 (positions 2, 5, 8 and 10).
  4. Each entry needs two earlier ones, so the table costs O(n) time, and only the last two entries need to be kept, so O(1) space.

Problem 2. Coins come in values 1, 5, 10 and 25, with as many of each as you like. In how many different ways can the total 60 be made? Two ways are the same when they use the same number of each coin, whatever the order. Give an integer.

Show the answer and the working

Answer: 73

  1. Build the table one coin at a time. Let ways(t) be the number of ways to make t using the coins considered so far. Adding a coin of value c updates ways(t) to ways(t) + ways(t - c), going upward through t. Starting with only 1-coins, every total has 1 way.
  2. Adding the 5-coin gives ways(t) = floor(t / 5) + 1. Carrying on with the 10-coin and then the 25-coin up to t = 60 gives the answer. The same number can be found by splitting on how many 25-coins are used.
  3. With no 25-coin, 60 is made from 1s, 5s and 10s: for 0 to 6 ten-coins the remaining amount can use 13, 11, 9, 7, 5, 3 and 1 ways of 5s, a total of 49. With one 25-coin, 35 is made in 8 + 6 + 4 + 2 = 20 ways. With two 25-coins, 10 is made in 3 + 1 = 4 ways.
  4. The total is 49 + 20 + 4 = 73. The table costs O(coins x total), here 4 x 60 steps. Looping over the coins on the outside is what keeps different orders of the same coins from being counted more than once.

Problem 3. What is the length of the longest common subsequence of BDCABAXQ and ABCBDABQX? A subsequence keeps the original order of its characters but may skip characters. Give an integer.

Show the answer and the working

Answer: 5

  1. Let L(i, j) be the longest common subsequence of the first i characters of the first text and the first j characters of the second. If the last characters match, L(i, j) = L(i - 1, j - 1) + 1. Otherwise it is the larger of L(i - 1, j) and L(i, j - 1). Row 0 and column 0 are 0.
  2. Fill a table with one row for each prefix of the first text (9 rows counting the empty prefix) and one column for each prefix of the second text (10 columns). The last column, which uses the whole second text, reads 1, 2, 2, 3, 4, 4, 5, 5 for the first 1 to 8 characters of the first text.
  3. The bottom right entry is 5. One such subsequence is B, C, B, A, Q: in the first text at positions 1, 3, 5, 6 and 8, and in the second text at positions 2, 3, 4, 6 and 8.
  4. The table has 8 x 9 cells and each costs O(1), so the time is O(mn).

Problem 4. Eight items have weights 3, 4, 5, 2, 6, 1, 7, 4 and values 40, 50, 70, 15, 75, 10, 95, 55, in the same order. A bag holds a total weight of at most 15, and each item can be used once. What is the largest total value that fits? Give an integer.

Show the answer and the working

Answer: 205

  1. Let best(c) be the largest value that fits in capacity c using the items considered so far. For each item of weight w and value v, update every capacity c from the top down to w: best(c) = the larger of best(c) and best(c - w) + v. Going downward uses each item at most once.
  2. Start with all zeros for capacities 0 to 15. After all eight items the table for capacities 0 to 15 reads 0, 10, 15, 40, 55, 70, 80, 95, 110, 125, 135, 150, 165, 175, 190, 205.
  3. The answer is best(15) = 205. One choice that reaches it is items 1, 3 and 7, with weights 3, 5 and 7 (total weight 15) and values 40, 70 and 95.
  4. The table has n x C cells, so the time is O(nC), here 8 x 15. Looping the capacity upward instead would let one item be used again and again, which is a different problem.

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

Questions

What is dynamic programming?

It is a way of solving a problem by breaking it into smaller problems, solving each smaller problem once and storing the answer. The Python documentation describes caching function results as a way to implement the technique.

What is the difference between memoization and a table?

Memoization is top down: you write the recursive rule and cache each answer the first time it is computed. A table is bottom up: you fill in the smaller answers first, in an order that makes each one available when needed.

How do I know a problem needs dynamic programming?

Look for a question about the best, the number of ways or whether something is possible, where the answer for the whole problem is built from answers for smaller versions that overlap. If a recursive solution would recompute the same small case again and again, caching those cases is the fix.

How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: what the state is, why the base cases are right and in which order the table is filled. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms