Skip to content
Home/Resources/Data Structures and Algorithms/Types of dynamic programming
Concept ยท Data Structures and Algorithms

Types of dynamic programming: memoization vs tabulation, and the DP families

Younus FardeenBy Younus FardeenUpdated 1 Dec 202610 min read
Short answer

Dynamic programming has two implementation styles, top-down memoization and bottom-up tabulation, and several problem families: 1D, 2D grid, knapsack-style, LCS-style, interval, bitmask and digit DP. The style changes how you code it, the family changes what the state looks like. Recognise the family from the input shape and the choice being made.

On this pageMemoization vs tabulation: the two stylesThe seven families of DP problemsHow to recognise a DP problemFrequently asked questions

People use "types of dynamic programming" to mean two different things, and most pages blur them. One is the implementation style: memoization (top-down) versus tabulation (bottom-up). The other is the problem family, which decides what your state looks like. This page separates them, measures the first with timing and call counts you can reproduce, and gives one running example for each of seven families.

If you want the full set of classic problems with solutions, see dynamic programming examples; for the basic idea, see what is dynamic programming. All code here ran on Python 3.9.

Memoization vs tabulation: the two styles

Memoization (top-down) writes the recursive solution and caches each result; tabulation (bottom-up) fills a table from the smallest sub-problem upward with loops. Both visit each state once, so they have the same big-O in most problems. They differ in what is easy to write, what can go wrong, and how many states they touch.

Memoization (top-down)Tabulation (bottom-up)
How it is writtenRecursion plus a cache (lru_cache or a dict)Loops filling an array or a few variables
States computedOnly the ones the answer actually needsAll states in the table
Recursion depthLimited by Python's recursion limit (1000 by default)None
Memory savingHard; the cache keeps every stateEasy; keep only the previous row
Hardest partGetting the cache key and base case rightFinding the correct fill order
Best whenState space is sparse or the order is unclearState space is dense and depth is large

Here is a measurement on Fibonacci(30). The naive recursion, the memoized version and a table all return 832040. The call counts are exact and repeatable; the timings are from one run on a laptop and will differ on your machine, but their order will not.

import time
from functools import lru_cache

calls = {"naive": 0, "memo": 0}

def fib_naive(n):
    calls["naive"] += 1
    return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)

@lru_cache(maxsize=None)
def fib_memo(n):
    calls["memo"] += 1
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)

def fib_tab(n):
    dp = [0, 1] + [0] * (n - 1)
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

def timed(fn, n, reps=1):
    t = time.perf_counter()
    for _ in range(reps):
        r = fn(n)
    return r, (time.perf_counter() - t) / reps * 1000

n = 30
r1, t1 = timed(fib_naive, n)
r2, t2 = timed(fib_memo, n)
r3, t3 = timed(fib_tab, n, reps=1000)
assert r1 == r2 == r3
print("calls: naive", calls["naive"], "memo", calls["memo"])
print(f"naive {t1:.1f} ms, memo {t2:.4f} ms, table {t3:.4f} ms (n={n})")
# memo vs tabulation on a problem that needs only some states
@lru_cache(maxsize=None)
def collatz_steps(n):
    return 0 if n == 1 else 1 + collatz_steps(n // 2 if n % 2 == 0 else 3 * n + 1)
collatz_steps(27)
print("memo only visited", collatz_steps.cache_info().currsize, "states for n=27")

Output from one run: calls: naive 2692537 memo 31, then naive 320.2 ms, memo 0.0169 ms, table 0.0026 ms (n=30), then memo only visited 112 states for n=27. The naive version made 2,692,537 calls for n=30; the memoized one made 31. The table was faster than the memo again, because it has no function-call overhead, but both are thousands of times faster than the naive recursion. The last line shows the memo advantage: the Collatz sequence from 27 only ever reaches 112 states, whereas a table would have to cover every number up to the largest value reached, which is 9,232 for 27.

Rule of thumb: start with memoization because it is the recurrence you already wrote, then convert to tabulation if you hit the recursion limit or need the memory savings. The recursion versus iteration page explains the depth problem in detail.

The seven families of DP problems

Each family below has one tested example. The family tells you the shape of the state: one index, a grid, an index plus a budget, two sequences, a range, a set of chosen items, or a prefix of digits.

FamilyState looks likeTypical problemsExample below
1DOne index iFibonacci, stairs, house robber, max subarrayCovered in the examples page
2D gridRow and column (r, c)Unique paths, minimum path sumGrid paths with an obstacle
Knapsack-styleIndex and remaining budget0/1 knapsack, subset sum, partition, coin changeSubset sum
LCS-styleTwo indices into two sequencesLCS, edit distance, longest palindromic subsequenceIn the examples page
IntervalA range (i, j)Matrix chain multiplication, burst balloons, palindrome partitioningMatrix chain
BitmaskA set of items stored as bits, plus the last itemTravelling salesman, assignment problems, small sets of up to about 20Tiny travelling salesman
DigitPosition in a number plus a tight flagCount numbers up to N with a digit propertyNumbers without a 4

2D grid DP

Count the ways to reach the bottom-right cell moving only right or down. A cell's count is the sum of the cell above and the cell to its left. Blocking a cell sets its count to zero. A 3 x 3 grid has 6 paths, 2 with the centre blocked, and a 10 x 10 grid has 48,620.

def two_sum_brute(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

def two_sum_pointers(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return [lo, hi]
        if s < target:
            lo += 1
        else:
            hi -= 1
    return []

nums = [2, 7, 11, 15, 19, 24]
print(two_sum_brute(nums, 26), two_sum_pointers(nums, 26))
print(two_sum_brute(nums, 100), two_sum_pointers(nums, 100))

Output: 6 2 48620.

Knapsack-style: subset sum

Can some subset of the numbers add up to the target? The state is the set of sums reachable so far. For [3, 34, 4, 12, 5, 2], a target of 9 is reachable (4 + 5) and 30 is not. This is the same take-or-skip choice as the knapsack in the examples page, with the value dropped.

def is_palindrome_brute(s):
    cleaned = "".join(ch.lower() for ch in s if ch.isalnum())
    return cleaned == cleaned[::-1]          # O(n) extra space

def is_palindrome_pointers(s):
    lo, hi = 0, len(s) - 1
    while lo < hi:
        while lo < hi and not s[lo].isalnum():
            lo += 1
        while lo < hi and not s[hi].isalnum():
            hi -= 1
        if s[lo].lower() != s[hi].lower():
            return False
        lo += 1
        hi -= 1
    return True                              # O(1) extra space

for text in ["A man, a plan, a canal: Panama", "race a car"]:
    print(is_palindrome_brute(text), is_palindrome_pointers(text))

Output: True False.

Interval DP: matrix chain multiplication

Multiplying matrices is associative, but the order changes the cost. Matrices of shapes 10 x 30, 30 x 5 and 5 x 60 cost 4,500 multiplications as (AB)C and 27,000 as A(BC). The state is a range of matrices, and the transition tries every split point inside it. Interval DP is the one family where the fill order is by range length, not by index.

def max_area_brute(h):
    best = 0
    for i in range(len(h)):
        for j in range(i + 1, len(h)):
            best = max(best, min(h[i], h[j]) * (j - i))
    return best

def max_area_pointers(h):
    lo, hi, best = 0, len(h) - 1, 0
    while lo < hi:
        best = max(best, min(h[lo], h[hi]) * (hi - lo))
        if h[lo] < h[hi]:      # the shorter wall cannot do better with a narrower gap
            lo += 1
        else:
            hi -= 1
    return best

h = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(max_area_brute(h), max_area_pointers(h))

Output: 4500.

Bitmask DP: a small travelling salesman

Find the shortest tour that visits all four cities once and returns to city 0. The visited set is stored as bits of an integer, so the state is (visited mask, last city). That is 2^n x n states, which is why bitmask DP works up to roughly 20 items and no further.

def remove_duplicates_brute(nums):
    unique = sorted(set(nums))               # O(n) extra space
    nums[:len(unique)] = unique
    return len(unique)

def remove_duplicates_pointers(nums):
    if not nums:
        return 0
    slow = 0
    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]
    return slow + 1                          # O(1) extra space

a = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
b = a[:]
k1, k2 = remove_duplicates_brute(a), remove_duplicates_pointers(b)
print(k1, a[:k1])
print(k2, b[:k2])

Output: 80.

Digit DP: numbers without a 4

How many integers from 0 to 1000 contain no digit 4? You walk the digits from the left, track whether the prefix still equals the limit's prefix (the tight flag), and cache on (position, tight). The brute-force count over 1001 numbers is printed beside it as a check: both give 730. The payoff is when the limit is 10^18 and brute force cannot run.

def three_sum_brute(nums):
    n, found = len(nums), set()
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if nums[i] + nums[j] + nums[k] == 0:
                    found.add(tuple(sorted((nums[i], nums[j], nums[k]))))
    return sorted(found)

def three_sum_pointers(nums):
    nums, out = sorted(nums), []
    for i in range(len(nums) - 2):
        if i and nums[i] == nums[i - 1]:
            continue                          # skip duplicate anchors
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            s = nums[i] + nums[lo] + nums[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                out.append((nums[i], nums[lo], nums[hi]))
                lo += 1
                hi -= 1
                while lo < hi and nums[lo] == nums[lo - 1]:
                    lo += 1
    return out

nums = [-1, 0, 1, 2, -1, -4]
print(three_sum_brute(nums))
print(three_sum_pointers(nums))

Output: 730 730.

How to recognise a DP problem

A problem is a DP candidate when it asks for a count, a minimum, a maximum or a yes/no, and a brute-force recursion would re-solve the same sub-problem many times. Use this checklist before you start coding.

  1. Does the question ask for the best, fewest, most or number of ways, rather than the list of all solutions? If you must list every solution, that is backtracking, not DP.
  2. Can you describe a smaller version of the same problem (a shorter prefix, a smaller amount, a narrower range)?
  3. Does the answer for the big problem depend only on answers to the smaller ones, not on the path taken to reach them?
  4. Do different choices lead to the same smaller problem? Draw the recursion tree for a tiny input and look for repeated nodes.
  5. Are the input sizes in the polynomial range (n up to a few thousand for O(n^2), or at most about 20 for a bitmask)?
  6. Would a greedy rule work? Test it against brute force on small inputs; if it fails once, it is DP. See greedy algorithms explained.

Keywords in the statement help but do not prove anything: "number of ways", "minimum cost", "longest", "can you reach" and "maximum profit" all point towards DP. The reliable test is the repeated sub-problem in the recursion tree.

Frequently asked questions

What are the main types of dynamic programming?

Two implementation styles, top-down memoization and bottom-up tabulation. Beyond those, problems fall into families by state shape: 1D, 2D grid, knapsack-style, LCS-style over two sequences, interval, bitmask and digit DP. Some books also list tree DP and DP on graphs, where the state is a node.

What is the difference between memoization and tabulation?

Memoization starts from the original problem, recurses, and stores each answer so it is never recomputed. Tabulation starts from the base cases and fills a table in order until it reaches the answer. Memoization computes only needed states; tabulation computes all of them but avoids recursion and makes memory trimming easy.

Which is faster, top-down or bottom-up DP?

Bottom-up is usually a little faster because it has no function-call overhead; in the Fibonacci(30) test above it was several times quicker than the memoized version. Both are thousands of times faster than naive recursion. Top-down can win when only a small part of the state space is ever reached.

Is memoization the same as caching?

Memoization is caching applied to the results of a pure function, keyed by its arguments. In Python, functools.lru_cache does exactly that. The word dynamic programming adds the requirement that the problem has overlapping sub-problems and an optimal substructure; caching alone does not.

What is 1D versus 2D dynamic programming?

The number of indices in the state. 1D problems such as stairs or house robber need one index, so one array or two variables. 2D problems such as grid paths, LCS or knapsack need two, so a grid. A 2D table can often be reduced to a single row if each row depends only on the one before.

What is bitmask DP used for?

It handles problems over a small set of items, usually 20 or fewer, where the state is which items are already used. The set is stored as the bits of an integer. The travelling salesman problem and assignment problems are standard examples, with 2^n times n states.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Dynamic programming examples

Eight classic DP problems with recurrences, Python code and real output

8 min read
Explainer

Dynamic programming explained

Memoization vs tabulation and five solved examples.

4 min read
Concept

Recursion vs iteration

Differences, same problems both ways, Python limits and when to choose each

7 min read