Skip to content
Visual explainer 4h to learn 5 steps

DP fundamentals: memoisation & 1D tabulation

Turn a recursive solution into memoised and bottom-up DP and solve classic 1D problems.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 40 of 54

In short

Dynamic programming solves problems whose subproblems overlap by computing each subproblem once and reusing it. Top-down DP adds a cache to a recursive solution; bottom-up DP fills a table in dependency order. Define the state, the recurrence, the base cases and the answer location before writing code.

Explained simply

Dynamic programming, or DP, is a fancy name for a simple habit: do not solve the same small problem twice. Write the answer down the first time, and look it up next time.

Take climbing stairs, where you can step 1 or 2 stairs at a time. The number of ways to reach stair 10 is the ways to reach stair 9 plus the ways to reach stair 8. A plain recursive solution asks for stair 8 many, many times. If you save each answer, every stair is computed just once.

DP fits when two things are true. First, the big problem breaks into smaller problems of the same kind (optimal substructure). Second, those smaller problems repeat (overlapping subproblems). If they never repeat, saving answers does not help, and plain recursion or divide and conquer is enough.

There are two ways to write it. Top-down: write the recursion and add a cache, called memoisation. Bottom-up: fill a list from the smallest case upwards, called tabulation. Both give the same answers and usually the same Big-O.

Press Play on a diagram to walk through it one step at a time.

FlowDesigning a DP solution
  1. 1
    State

    dp[i] means best answer for first i items.

  2. 2
    Recurrence

    How dp[i] uses smaller states.

  3. 3
    Base cases

    dp[0], dp[1].

  4. 4
    Order

    Fill so dependencies come first.

  5. 5
    Answer

    dp[n] or max over dp.

CompareTop-down versus bottom-up
Memoisation
  • Recursion plus cache
  • Computes only needed states
  • Risk of deep recursion
Tabulation
  • Loops over a table
  • No recursion overhead
  • Easy space optimisation
FlowHouse robber on [2, 7, 9, 3, 1]
  1. 1
    House 2

    best = max(0, 0 + 2) = 2

  2. 2
    House 7

    best = max(2, 0 + 7) = 7

  3. 3
    House 9

    best = max(7, 2 + 9) = 11

  4. 4
    House 3

    best = max(11, 7 + 3) = 11

  5. 5
    House 1

    best = max(11, 11 + 1) = 12

CompareThree kinds of DP question
Count ways
  • Add the options
  • Base: one way to do nothing
  • Climbing stairs, decode ways
Best value
  • max or min of options
  • Base: 0 or infinity
  • House robber, coin change
Is it possible
  • any option is True
  • Base: empty is True
  • Word break, subset sum

In depth

How bad is it without a cache?

The naive Fibonacci function fib(n) = fib(n - 1) + fib(n - 2) makes a number of calls that grows like 1.618^n (the golden ratio to the power n). fib(30) already makes 2,692,537 calls, and fib(50) would take hours in Python. Yet there are only 51 different values, fib(0) to fib(50).

The tree of calls shows why: fib(3) appears twice under fib(5), fib(2) three times, and the repeats double with each level. A cache turns that tree into a straight line. Each distinct state is computed once and every later request is a dictionary lookup.

This gives the basic DP cost rule: time = number of states x work per state. Fibonacci has n states and O(1) work each, so O(n).

MapCalls made by naive fib(5)
fib(5)
  • fib(4)
    • fib(3): computed again below
    • fib(2)
  • fib(3)
    • fib(2): third time overall
    • fib(1)

Memoisation in Python

functools.cache (Python 3.9 and later) is a decorator that stores results keyed by the arguments. It is the same as lru_cache(maxsize=None). Arguments must be hashable, so pass a tuple or an index instead of a list. Define the cached helper inside the main function when it depends on input data; then each call of the main function gets a fresh cache.

The catch is recursion depth. CPython's default limit is 1,000 frames, so a top-down DP over 10,000 states raises RecursionError. sys.setrecursionlimit can raise it, but very deep recursion can still crash the interpreter, which is a good reason to switch to bottom-up for long 1D problems.

  • @cache or @lru_cache(maxsize=None)
  • Arguments must be hashable: ints, strings, tuples
  • f.cache_clear() empties the cache
  • Default recursion limit: 1,000

From recursion to a table

Converting top-down to bottom-up is mechanical. The function's arguments become the table's indexes. The recursion's base cases become the first table entries. The recursive calls tell you which entries each cell needs, so you loop in an order where those are already filled. Finally, the original call tells you which cell holds the answer.

For house robber, rob(i) = max(rob(i - 1), rob(i - 2) + nums[i]). Each state needs smaller indexes, so loop i upwards. Bottom-up has no recursion limit and less overhead per state, while top-down only computes states that are actually needed, which can be far fewer in some problems.

FlowTop-down to bottom-up
  1. 1
    Arguments

    Become table indexes: dp[i].

  2. 2
    Base cases

    Fill dp[0], dp[1] first.

  3. 3
    Recursive calls

    Show which cells each cell reads.

  4. 4
    Loop order

    Fill so those cells come first.

  5. 5
    First call

    Its state is the answer cell.

Shrinking the memory

Look at which earlier cells the recurrence reads. If dp[i] only reads dp[i - 1] and dp[i - 2], you never need the whole list, only the last two values. Keep two variables and shift them forward each step, and space drops from O(n) to O(1).

The same idea works for any fixed window: if dp[i] reads back k steps, keep a list or deque of the last k values for O(k) space. The trade-off is that you lose the full table, so you cannot reconstruct which choices led to the answer. If you need the actual choices, keep the table or a separate list of decisions.

A small catalogue of 1D DP

Most 1D problems use one of two state meanings. "dp[i] = answer for the first i items" fits house robber and decode ways. "dp[i] = best answer that ends exactly at i" fits maximum subarray (Kadane's algorithm: dp[i] = max(a[i], dp[i - 1] + a[i]), then take the max over all i) and the longest increasing subsequence.

The combining operation depends on the question. Counting ways adds the options. Finding a best value takes max or min. Asking whether something is possible uses or (any option works). Spotting which of the three you need is half of writing the recurrence.

  • Count ways: dp[i] = sum of options
  • Best value: dp[i] = max or min of options
  • Is it possible: dp[i] = any option is True

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Spot overlapping subproblems and optimal substructure~50m
  2. 2
    Memoise with a dict or lru_cache~50m
  3. 3
    Convert to bottom-up tabulation~50m
  4. 4
    Solve climbing stairs and house robber~50m
  5. 5
    Reduce space to O(1)~50m

Key points

  • Time is roughly number of states times work per state.
  • House robber: dp[i] = max(dp[i-1], dp[i-2] + nums[i]), O(n) time.
  • When dp[i] depends only on the last two states, space drops to O(1).
  • functools.cache memoises a pure function in one line.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from functools import cache

@cache
def climb(n):                     # top-down, O(n)
    return 1 if n <= 1 else climb(n - 1) + climb(n - 2)

def rob(nums):                    # bottom-up, O(n) time, O(1) space
    prev2 = prev1 = 0
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1

print(climb(10), rob([2, 7, 9, 3, 1]))  # 89 12

Decode ways

Letters are coded A = 1 to Z = 26. How many ways can "226" be decoded? State: dp[i] = ways to decode the first i characters. dp[0] = 1 (the empty string has one decoding). A single digit d adds dp[i - 1] if d is not 0. A pair of digits adds dp[i - 2] if it is between 10 and 26. For "226": dp[1] = 1 (B), dp[2] = 2 (BB, V), dp[3] = 3 (BBF, BZ, VF). A 0 that cannot pair, like in "06", gives 0.

python
def num_decodings(s):              # O(n) time, O(n) space
    n = len(s)
    dp = [1] + [0] * n                 # dp[i]: ways for s[:i]
    for i in range(1, n + 1):
        if s[i - 1] != "0":
            dp[i] += dp[i - 1]
        if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:
            dp[i] += dp[i - 2]
    return dp[n]

print(num_decodings("226"), num_decodings("06"), num_decodings("11106"))  # 3 0 2

Word break with memoisation

Can "leetcode" be split into words from {"leet", "code"}? State: can(i) = can the suffix starting at i be split? can(len(s)) is True. For each word that matches at position i, try can(i + len(word)). The cache makes sure each starting index is solved once, so there are n + 1 states and each tries every word. Without the cache, an input like "aaaa...ab" with words a, aa, aaa makes the search exponential.

python
from functools import cache

def word_break(s, words):
    @cache
    def can(i):
        if i == len(s):
            return True
        return any(s.startswith(w, i) and can(i + len(w)) for w in words)
    return can(0)

print(word_break("leetcode", ["leet", "code"]))                    # True
print(word_break("catsandog", ["cats", "dog", "sand", "and", "cat"]))  # False

Quick reference

  • DP needs optimal substructure plus overlapping subproblems
  • Time = number of states x work per state
  • Write the state in words first: dp[i] = ... for the first i items
  • @functools.cache memoises; arguments must be hashable
  • CPython's default recursion limit is 1,000: go bottom-up for long inputs
  • dp[i] reads only dp[i-1] and dp[i-2]: keep two variables, O(1) space
  • Count ways: add; best value: max or min; feasibility: any
  • Kadane: best ending here = max(a[i], best ending before + a[i])

Common mistakes

  • Starting to code before the state is clearly defined.
  • Caching on mutable arguments such as lists, which are unhashable.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which pair of properties makes DP a good fit?

Question 2

2A top-down DP has 10,000 states in a chain. What usually goes wrong in CPython?

Question 3

3Why does @cache fail on def f(nums: list, i: int)?

Question 4

4dp[i] = max(dp[i - 1], dp[i - 2] + a[i]). How much extra space does the optimised version need?

Question 5

5Decode ways for "12". What is the answer?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Tribonacci: T0 = 0, T1 = 1, T2 = 1, and Tn = Tn-1 + Tn-2 + Tn-3. Write it with functools.cache and print T25.

  2. Exercise 2medium

    cost[i] is the price of stepping on stair i. You may start at stair 0 or 1 and climb 1 or 2 stairs at a time. Return the minimum cost to get past the last stair, in O(1) space. Example: [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] gives 6.

  3. Exercise 3hard

    House robber II: the houses form a circle, so the first and last are neighbours. Return the most you can rob. Examples: [2, 3, 2] gives 3, [1, 2, 3, 1] gives 4.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I write DP top-down or bottom-up?
Top-down is faster to write and only visits needed states, so it is great in interviews. Bottom-up avoids recursion limits, runs faster in Python and makes space optimisation easy.
How do I find the DP state?
Ask what information you need to describe the remaining problem. Usually it is a position i, sometimes plus a small extra like remaining capacity or a flag; that list of values is the state.
Is memoisation the same as caching?
Yes, memoisation is caching applied to a function's results, keyed by its arguments. In Python, functools.cache does it for you.
Why is it called dynamic programming?
Richard Bellman chose the name in the 1950s. "Programming" meant planning, as in a schedule, not writing code, and he picked "dynamic" partly because it sounded impressive.

Go deeper

ShareXLinkedInWhatsApp