Skip to content
Coding Pattern:

Dynamic Programming

This pattern has a cheat sheet you can unlock.

Overview

Dynamic programming makes recursion faster by saving results you've already computed. It uses extra space to store them.

Dynamic programming comes in 1D and 2D versions. In 1D, we "remember" function results by storing them in a one-dimensional list. Caching function results like this is called memoization.

Note

Dynamic programming is one of the hardest patterns to master, especially in higher dimensions. It's very different from other questions. Don't worry if you don't understand it the first time.

There are two ways to approach dynamic programming:

  1. Top Down Dynamic Programming starts at the end of the problem and works backward. It saves each answer as it goes. You can think of it as recursion plus a list of saved answers.
  2. Bottom Up Dynamic Programming starts at the beginning of the problem and works toward the end. It uses a for loop instead of recursion.

We'll teach the top down approach because it's the easier of the two.

Note

Bottom up is faster in practice because recursion has overhead. In an interview that difference rarely matters. Top down is also easier to write. Remember to look up both and see which one you prefer.

Pattern concept

We'll use the Fibonacci sequence to show how dynamic programming works.

In the Fibonacci sequence, each number is the sum of the two numbers before it. It starts like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...

Dynamic Programming Slide 1: Let's define a function fib(n) that finds the nth Fibonacci number. fib(0) = 0, fib(1) = 1, fib(2) = 1, fib(3) = 2, fib(4) = 3, fib(5) = 5, fib(6) = 8, and fib(7) = 13.
1 / 32

You can also use the ← and → arrow keys.

Solution template

# Recursive Helper Function
def fib(i: int, memo: List[int]) -> int:
  # Base Case Check: 
  # Return a value if is the simplest case.
  if i <= 1:
    memo[i] = i
    return memo[i]
  
  # Memoization Check: 
  # Check if computed this case before.
  if memo[i]:
    return memo[i]
    
  # Recurrence Relation:
  # Break down the problem into subproblems.
  result = fib(i - 1, memo) + fib(i - 2, memo)
  memo[i] = result
  return result

# Original Function
def get_fibonacci_number(n: int):
  # Memoization List Initialization: 
  # Initialize the list to store our computations.  
  memo = [None] * (n + 1)
  result = fib(n, memo)
  print('memo:', memo)
  return result
  
print(get_fibonacci_number(5))
    
main.py

A dynamic programming solution has three main steps. Once you figure out all three, you can solve the problem:

  • Recursive Helper Function

    Top down dynamic programming always passes a memo list down through the recursion. That's why it needs a separate helper function.

    • Base Case Check

      The base case is the simplest case. It's where the recursion stops and returns an answer directly.

      Here the base cases are fib(0) = 0 and fib(1) = 1.

      You can also fill in memo for these cases here.

    • Memoization Check

      If we've already computed this case, return the answer we saved.

    • Recurrence Relation

      If the code gets here, this case isn't a base case and we haven't computed it yet.

      For Fibonacci, the recurrence relation is the sum of the previous two numbers.

      Most of the time, this step is a sum of the results of two functions.

      Note

      The recurrence relation is usually the hardest part. You get better at it with practice. Try reading a lot of dynamic programming questions and writing only the recurrence relation for each one.

  • Memoization List Initialization

    Set up the memo list so you can tell whether a value has been computed yet. The easiest way is to fill it with None. To make a list of size n, multiply a list holding None by n: memo = [None] * n. For Fibonacci we use n + 1. The list needs a spot for every index from 0 through n.

    Note

    For a 2D list with rows x cols, use a list comprehension:

    memo = [[None] * cols for i in range(rows)]

    Don't use:

    memo = [[None] * cols] * rows

    That puts the same inner list in every row. Changing one row changes all of them.

How to identify

Does the problem involve any of these?

  • Recursion based on previous states (you can break it down into similar subproblems)
    • Fibonacci Numbers: Find the nth Fibonacci number by adding the two numbers before it. You find those two numbers the same way.
    • Longest Increasing Subsequence: Find the longest increasing subsequence in a list (by checking whether each element can extend an increasing subsequence that ends before it).
    • Coin Change: Find the minimum number of coins needed to add up to a given amount (by solving for smaller and smaller amounts).
  • Choosing between several moves on a 1D or 2D grid
    • Climbing Steps: Find the number of ways to reach the nth step of a set of stairs.
    • Unique Paths: Find the number of unique paths from the top-left corner to the bottom-right corner of a grid, moving only down or right.

Note

Most 1D dynamic programming problems take O(n) time because each value is computed at most once.