Unit 2 of 9 · about 3 hours · implement

Memoization, tabulation and dependency order

Memoized recursion dies near depth 1000 in CPython. Tabulation with an explicit order is the form that survives production-sized inputs.

You'll be able to

  • Implement memoized and tabulated forms of one recurrence and show they compute the same values.
  • Read dependencies off a recurrence and state the evaluation order before writing the loop.
  • Predict when memoized recursion hits the Python recursion limit and switch to tabulation.

Covers

Dependency order and topological evaluationMemoized recursion and state identityBottom-up tabulation and iteration order
1

Read

In this order, only the parts listed

0 of 3 done

  1. Fibonacci from naive recursion to iterationAlgorithms - dynamic programming

    Section 3.1 (pp. 97-102): RecFibo, the call-count argument, MemFibo, IterFibo and IterFibo2

    Skip Section 3.2, the matrix-squaring speedup (p. 103), until the limits unit.

  2. The four-step conversion to a tableDSA Handbook - dynamic programming

    The four-step conversion: dependency DAG, topological order, loop, array; Tracing the table fill on

  3. The default 1000-frame limitPython sys: recursion limit

    sys.getrecursionlimit and sys.setrecursionlimit: the limit guards the C stack, and the highest safe value is platform-dependent. Check the current value with sys.getrecursionlimit() (1000 on CPython 3.13).

2

Focus on

  • Memoization visits states lazily in recursion order; tabulation visits them eagerly in an order you choose. Both compute the same values.
  • The dependency DAG must be acyclic. For the edges run to smaller indices, so increasing is a valid topological order.
  • A Python frame per index means depth- recursion needs a limit above . Set it once at module top level, never per function.
  • State count times per-state work gives total time: states at each is for Fibonacci.
Common mistakes · 3
  • Reusing one global memo across calls for state that is not absolute. Stale entries from the previous call return wrong answers; build a fresh memo per call.
  • Returning a mutable object from a memoized function and letting the caller mutate it. Later cache hits return the mutated object.
  • Copying a top-down recurrence into a bottom-up loop without flipping the direction. A left-to-right loop reading reads uninitialized cells.
3

Try it yourself

Closed-book, before checking anything

Closed-book in Python 3.13, write memoized and tabulated fib. Both give . At the default limit of 1000, raises RecursionError; with the limit raised once to 10000 the memoized form returns a 523-digit integer, and the tabulated form returns the same digits. Assert the two results are equal.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1. under the default limit: what happens and why?Answer

    RecursionError. The chain runs 2500 frames deep before the first base case returns, and the default limit is 1000. The cache cannot help because no call has returned yet.

  2. 2.When is tabulation better than memoization if both are ?Answer

    When the topological order is obvious and the input is deep or call overhead matters. Tabulation has no recursion stack and pays one index per step instead of one frame per state.

  3. 3.Your bottom-up loop reads left to right and returns garbage. What went wrong?Answer

    The loop order violates the dependency direction. Either iterate right to left or rewrite the recurrence so it reads already-filled cells.

  4. 4.Why must a memoized function be pure?Answer

    The cache swaps recomputation for lookup. If the result depends on hidden mutable state, the stored value is stale for the next call and the answer changes.

5

Practice

  • LeetCode 509 - Fibonacci Number

    Implement memoized and tabulated forms; check (answers 1, 2, 3), then submit.

    Compare both forms on . After submitting, use the DSA Handbook dp-recursion-to-memo ladder as the reference.

  • LeetCode 1137 - N-th Tribonacci Number

    Extend the window to three predecessors; check (answer 4) and (answer 1389537), then submit.

    Carry three rolling values in the tabulated form. After submitting, compare with the DSA Handbook fixed look-back section.

You're done when

Both forms agree on from a blank file, and you can state the order and the limit behavior without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 5 more in the section
  • DSA Handbook - dynamic programmingHandbook Academy · primary

    Study Part 9 in order from state and recurrence through sequence, grid, tree and bitmask families. For every example, close the page and reconstruct the state, transition and evaluation order.

  • Algorithms - dynamic programmingJeff Erickson · required

    Use the dynamic-programming chapter to derive states and recurrences from first principles and to separate DP from greedy reasoning and shortest paths.

  • Python sys: recursion limitPython Software Foundation · reference

    Read sys.getrecursionlimit and sys.setrecursionlimit: the limit guards the C stack and its safe maximum is platform-dependent. Check the default with getrecursionlimit (1000 on CPython 3.13), raise it once for memoized DP, or switch to tabulation for deep inputs.

Also in this section

  • AlgoMaster DSA - dynamic programming sliceAlgoMaster · required

    Attempt Coin Change, Longest Common Subsequence and House Robber III cold. Write the state, transition, base case and evaluation order first; compare against brute force on small inputs and reconstruct a witness when available.

  • Hypothesis - exhaustive and differential DP testsHypothesis · support

    Generate small valid instances, compare memoized, tabulated and exhaustive results, and retain shrunk failures for wrong state, base case, order and compression defects.

  • NeetCode - unseen mixed problemsNeetCode · optional

    Use two tag-hidden mixed problems as the final transfer test. One must require rejecting a tempting greedy or insufficient-state solution with a counterexample.

  • Erickson lecture note D - Advanced Dynamic ProgrammingJeff Erickson · reference

    Read Section D.1 (Saving Space: Divide and Conquer) for the Hirschberg Half-table split that recovers an optimal edit sequence in space.

  • Erickson lecture note J - Approximation AlgorithmsJeff Erickson · reference

    Read Section J.1 (Load Balancing) for the Partition reduction that makes exact scheduling NP-hard, the GreedyLoadBalance heuristic, and Theorem J.1 with its factor-2 proof.