Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Memoization to Tabulation: DP Conversion

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Introduction

Welcome back. In the previous lesson, we mastered the top-down approach to Dynamic Programming using memoization. You learned how to take a brute-force recursive solution and make it efficient by caching the results of subproblems. This is often the most intuitive way to start solving a DP problem.

In this lesson, we will explore the second major DP technique: bottom-up DP, or tabulation. While memoization starts with the main problem and recursively breaks it down, tabulation starts with the smallest, simplest subproblems and iteratively builds up to the final solution.

You might wonder why we need another method if memoization works. There are several key reasons that are highly relevant in an interview context:

  • Performance: Tabulation uses iteration instead of recursion, which avoids the overhead of function calls and eliminates the risk of a stack overflow error for problems with very deep state transitions.
  • Optimization: The iterative structure of tabulation often makes it easier to see patterns in state dependencies, which is the key to performing space optimizations—a common follow-up question in interviews.

Our goal is to learn a systematic, mechanical process for converting a top-down, memoized solution into a bottom-up, tabular one. The core logic remains the same; we are simply changing the order of computation.

Let's start with a high-level visual comparison.

Visual Comparison of Top-Down vs. Bottom-Up Dynamic Programming
This image shows the conceptual difference between the two approaches. Top-down (memoization) starts from the main problem and moves down to the base cases. Bottom-up (tabulation) starts with the base cases and builds up to the main problem's solution.

From Memoization to Tabulation: The Core Idea

The key insight is that both memoization and tabulation solve the exact same set of subproblems. The only difference is the order. Memoization solves them as the recursion unfolds (lazily), while tabulation solves them in a predetermined, iterative order, starting from the simplest cases.

This means if you have a correct recurrence relation for your memoized solution, you already have almost everything you need for the tabular version. The main challenge is figuring out the correct order to fill the table.

Let's use the familiar Fibonacci sequence to illustrate this. The video below first gives a quick review of the top-down approach before introducing the bottom-up concept.

11. Top-Down vs. Bottom-Up (Dynamic Programming for Beginners)

Andrey Grehov's video, 'Top-Down vs. Bottom-Up', clearly explains the conceptual shift from recursion with caching to iteration with a table.

Please watch from 04:46 to 10:26. The first part (until 07:13) is a quick refresher on top-down memoization for Fibonacci. The second part (from 07:13) introduces the bottom-up (tabulation) approach. Focus on the key ideas: starting with base cases, iterating, and filling a table (an array in this case).

As the video explained, the bottom-up approach involves:

  1. Initializing a "table" (e.g., an array dp) to store the results of subproblems.
  2. Seeding the table with the base case values (e.g., dp[0] = 0, dp[1] = 1).
  3. Iterating from the base cases upwards, filling the table using the recurrence relation (dp[i] = dp[i-1] + dp[i-2]).

Here is the Go implementation from the same video, which perfectly demonstrates this process.

11. Top-Down vs. Bottom-Up (Dynamic Programming for Beginners)

Let's see the bottom-up Fibonacci solution in Go.

Watch from 14:01 to 14:58. Notice how the logic is encapsulated in a simple for loop, building the dp slice from the pre-filled base cases. This is the essence of tabulation.


A Systematic Framework for Conversion

While Fibonacci is straightforward, converting more complex 2D or 3D DP problems can be tricky. The key is to have a repeatable framework. The process isn't about re-inventing the solution; it's a mechanical translation.

We can break this translation into three main steps, which are based on analyzing the recurrence relation you already developed for the memoized solution.

The following text provides an excellent, concise summary of this universal process.

A Universal Rule to Convert Memoization DP into Tabulation

The article 'A Universal Rule to Convert Memoization DP into Tabulation' by Vinay provides a clear, step-by-step guide that we will follow.

Please read the sections 'Why Memo -> Tabulation feels confusing', 'The Core Idea', and 'The Universal 6-Step Rule'. We will be focusing on a condensed 3-step version of this rule, but understanding all six steps provides a solid foundation.

Let's formalize our 3-step conversion framework:

Step 1: Define the DP Table and Initialize Base Cases

  • Identify State: The parameters of your recursive function f(param1, param2, ...) define the dimensions of your DP table. If your function is f(i, j), your table will be dp[i_size][j_size].
  • Determine Size: The range of values for each parameter determines the size of each dimension. For a parameter i from 0 to n, you'll need a dimension of size n+1.
  • Initialize Base Cases: The return statements in your recursion's base cases become the initial values you set in your DP table. For example, if if (i == n) return 0;, you would initialize dp[n][...] = 0.

This video provides a detailed walkthrough of this first step.

Recursive to iterative dynamic programming in 3 steps!

The video 'Recursive to iterative dynamic programming in 3 steps!' by DecodingIntuition gives a fantastic breakdown of how to methodically create the DP table.

Watch from 01:23 to 04:56. The video uses the Coin Change problem as an example. Focus on how the parameters of the recursive function and their bounds are used to determine the exact dimensions and size of the dp array.

Step 2: Determine the Loop Order from Dependencies

This is the most critical and often the most challenging step. The order of your loops must guarantee that you compute the value for a subproblem before it's needed to compute a larger problem.

The rule is simple: Your loops must run in the reverse direction of the recursive dependencies.

  • If your recurrence f(i) depends on f(i-1) (e.g., f(i) = ... + f(i-1)), your loop for i must iterate forwards (e.g., for i := 1 to n).
  • If your recurrence f(i) depends on f(i+1) (e.g., f(i) = ... + f(i+1)), your loop for i must iterate backwards (e.g., for i := n-1 down to 0).

The same logic applies to multiple dimensions.

Recursive to iterative dynamic programming in 3 steps!

Let's continue with the same video to understand how to derive the loop order.

Watch from 04:56 to 11:10. This is the most important part of the lesson. Pay close attention to how analyzing the recursive calls—num_ways(i, x - coin) and num_ways(i + 1, x)—dictates the direction of the for loops for i and x.

Step 3: Translate the Recurrence Relation

With the table created and the loop order set, the final step is to fill in the body of the loops. You simply copy the recurrence relation from your memoized solution, replacing recursive calls with lookups into your DP table.

  • A recursive call f(i, j) becomes a table lookup dp[i][j].
  • The assignment to the memo cache becomes the assignment to the current cell in the table: memo[i][j] = result becomes dp[i][j] = result.

Recursive to iterative dynamic programming in 3 steps!

This final clip from the video shows how to translate the logic inside the loops.

Watch from 11:10 to 12:16. See how the recursive calls are directly replaced by array lookups. This step is usually the most straightforward part of the conversion.


Application: Converting a 2D Go Example

Let's apply this 3-step framework to the "chocolate eating" problem from our previous lesson. This will solidify the process using a familiar, non-trivial example in Go.

Recall the memoized function signature and recurrence:
func JoyMemo(choco []int, i, j int, memo [][]result)
res = max(day*choco[i] + JoyMemo(i+1, j, ...), day*choco[j-1] + JoyMemo(i, j-1, ...))

Let's apply our framework:

  1. Define Table: The state is (i, j), where i runs from 0 to n-1 and j runs from 1 to n. We'll create a 2D table memo[n][n+1].

  2. Determine Loop Order:

    • The term JoyMemo(i+1, j) means memo[i][j] depends on memo[i+1][j]. The dependency for i is on a larger value (i+1). Therefore, our i loop must run in reverse: from n-1 down to 0.
    • The term JoyMemo(i, j-1) means memo[i][j] depends on memo[i][j-1]. The dependency for j is on a smaller value (j-1). Therefore, our j loop must run forwards: from i+2 up to n.
  3. Translate Recurrence: The recursive logic max(...) becomes the body of our nested loops, with JoyMemo calls replaced by memo table lookups.

Now, examine the Go code that implements this exact logic.

Dynamic programming [step-by-step example]

The article 'Dynamic programming [step-by-step example]' from the previous lesson also provides the tabulation solution. Let's analyze it with our new framework in mind.

Read the section 'Dynamic programming with tabulation' and study the JoyTab function. Confirm that the loop orders (for i := n - 1; i >= 0; i-- and for j := i + 2; j <= n; j++) match the dependencies we just identified. Note how the recursive calls are replaced with memo[i+1][j].joy and memo[i][j-1].joy.


Conclusion

In this lesson, we demystified the process of converting a top-down, memoized DP solution into a bottom-up, tabular one. By understanding that this is a mechanical translation, not a reinvention, you can reliably implement the more performant iterative approach.

Key Takeaways:

  • Tabulation vs. Memoization: Tabulation is an iterative, bottom-up approach that avoids recursion overhead and stack limits. Memoization is a recursive, top-down approach that can be more intuitive to write initially.
  • The Conversion Framework: The conversion is a systematic process grounded in the recurrence relation:
    1. Define Table: The recursive function's parameters and their ranges define the DP table's dimensions and size. Base cases seed the table.
    2. Determine Loop Order: This is the key step. The loop direction for each state variable is the reverse of its dependency in the recurrence relation.
    3. Translate Logic: Replace recursive calls with table lookups inside the loops.
  • Staff-Level Perspective: In an interview, being able to discuss the trade-offs (recursion overhead vs. complex loop logic) and fluently convert between the two approaches demonstrates a deep command of DP.

You now have two powerful techniques in your DP toolkit. While tabulation is often preferred for its performance and optimization potential, it's wise to start by thinking recursively to find the recurrence relation, as suggested in the Andrey Grehov video.

In our next lesson, we will leverage the iterative nature of tabulation to tackle space optimization, a crucial technique for passing interviews for memory-constrained problems. We will see how to reduce the space complexity of many DP problems from, for example, to .