Introduction
Welcome back! In our previous lesson, we established the diagnostic framework for Dynamic Programming, focusing on how to identify problems that possess optimal substructure and overlapping subproblems. You learned to spot the signatures of a DP problem, a crucial first step before writing any code.
Now that you can diagnose a problem as a candidate for DP, it's time to implement a solution. In this lesson, we will cover the first of two major DP techniques: top-down DP with memoization.
This approach is often the most intuitive way to begin your DP journey. It starts with the brute-force recursive solution you practiced identifying and systematically optimizes it. The core idea is to cache the results of subproblems to avoid re-computing them. Given your experience with caching strategies in distributed systems, the concept of memoization should feel very familiar—we are simply applying it at the function-call level to eliminate redundant work.
Our goal is to master the pattern of converting a naive recursive function into a highly efficient memoized one.
From Recursion to Memoization: The Core Idea
Let's revisit our familiar example: the Fibonacci sequence. The naive recursive solution is:
func fib(n int) int {
if n <= 1 {
return n
}
// This leads to re-computing fib(n-1) and fib(n-2) repeatedly
return fib(n-1) + fib(n-2)
}
As we saw in the last lesson, this has a time complexity of due to the massive number of overlapping subproblems. Memoization's goal is to solve each subproblem—like fib(3)—exactly once.
The video below provides an excellent walkthrough of this process. It starts by visualizing the redundant calls in the recursion tree (which will be a quick review for you) and then introduces the concept of storing results to avoid this waste.
DP 1. Introduction to Dynamic Programming | Memoization | Tabulation | Space Optimization Techniques
The YouTube channel 'take U forward' offers a detailed explanation of how to convert a simple recursive solution into a memoized one. We will watch the first part, which covers the 'why' and 'what' of memoization.
Watch from 05:27 to 14:44. The first part (until 12:20) recaps the problem of overlapping subproblems. The second part (from 12:20) introduces the core idea of memoization: using a data structure (like an array or map) to store the results of subproblems.
The 3-Step Memoization Pattern
As the video illustrates, converting a recursive solution to a memoized one is a repeatable, mechanical process. It involves three key steps:
-
Define the State and Create a "Memo": Identify the parameters that uniquely define a subproblem. This is your "state." Create a data structure (often an array or a map) to act as a cache, or "memo," to store the results for each state. Initialize it with a sentinel value (e.g., -1 or
nil) to signify that the subproblem has not yet been solved. -
Check the Memo: At the very top of your recursive function, before the base cases, check if the result for the current state already exists in your memo. If it does (i.e., it's not the sentinel value), return the stored result immediately. This is the cache hit.
-
Store in the Memo: If the result was not in the memo (a cache miss), proceed with the normal recursive computation. Then, just before returning the newly computed result, store it in the memo.
Let's see this pattern in action. The next segment of the video demonstrates exactly how to apply these three steps to the Fibonacci code.
DP 1. Introduction to Dynamic Programming | Memoization | Tabulation | Space Optimization Techniques
This clip continues from where we left off, providing a line-by-line implementation of the 3-step memoization pattern.
Watch from 14:44 to 22:22. Pay close attention to how the DP array is declared, how the check is added at the start of the function, and how the result is stored before returning. The video also shows how to pass the memoization table as a parameter, which is standard practice in interviews to avoid global variables.
Here is a summary of the pattern applied to the Fibonacci problem, which you can use as a template:

Complexity Analysis of Memoization
Why is this so much better? Let's analyze the complexity.
- Time Complexity: With memoization, each subproblem
fib(i)forifrom0tonis computed exactly once. When we encounter it again, the lookup is a constant time operation . Since there are unique subproblems, the total time complexity is brought down from to . - Space Complexity: We use two sources of extra space: the recursion call stack and the memoization table.
- The maximum depth of the recursive calls will be . This contributes space.
- Our memoization array also stores values, contributing another space.
- The total space complexity is .
This short video from HackerRank provides a succinct recap of this complexity analysis.
Algorithms: Memoization and Dynamic Programming
This HackerRank video offers another clear explanation of the runtime and space complexity improvements gained from memoization.
Watch from 00:12 to 04:05. This clip reinforces the time complexity change and provides a very clear explanation of why the space complexity for both the naive and memoized solutions is O(n).
Applying Memoization to a 2D Problem
The memoization pattern isn't limited to 1D problems like Fibonacci. Let's apply it to a common 2D interview problem: Unique Paths in a Grid with Obstacles.
Problem: You are given an m x n grid. You start at (0, 0) and want to go to (m-1, n-1). You can only move down or right. Some cells are blocked as obstacles. How many unique paths exist?
-
Recursive Formulation (Brute Force):
- The state is defined by our current position
(row, col). - The number of ways to reach the destination from
(row, col)isways(row+1, col) + ways(row, col+1). - Base Cases:
- If
(row, col)is out of bounds or an obstacle, return0(no paths from here). - If
(row, col)is the destination(m-1, n-1), return1(we found one valid path).
- If
- The state is defined by our current position
-
Applying the Memoization Pattern:
- State & Memo: The state is
(row, col). We need a 2D memo:memo[m][n]. - Check: At the start of
ways(row, col), check ifmemo[row][col]has been computed. If so, return it. - Store: After computing
result = ways(row+1, col) + ways(row, col+1), store it:memo[row][col] = result, then returnresult.
- State & Memo: The state is
The HackerRank video we just looked at continues to explain this exact problem.
Algorithms: Memoization and Dynamic Programming
Let's continue with the HackerRank video, which now applies the same logic to the 2D grid path problem.
Watch from 04:05 to 07:40. Observe how the 1D memoization pattern directly translates to a 2D problem. The state now has two parameters, so the cache becomes a 2D array.
The time complexity becomes because we solve each (row, col) subproblem once. The space complexity is also for the memoization table and the recursion stack.
Idiomatic Go Implementation
Let's look at how to implement this pattern cleanly in Go, using a slightly more complex problem. This will help solidify the concept and prepare you for problems where the state is not as simple as a single index.
The following article introduces a problem and then walks through its recursive and memoized Go solutions.
Dynamic programming [step-by-step example]
The article 'Dynamic programming [step-by-step example]' from yourbasic.org uses a 'chocolate eating' problem to demonstrate the transition from a naive recursive solution to a memoized one in Go.
Read the sections 'Problem', 'Recursive algorithm', and 'Dynamic programming with memoization'. First, understand the problem and its inefficient recursive solution. Then, analyze the provided JoyMemo function. Notice how it uses a 2D slice memo[][]result to store both the optimal value and the choice made, and how the state is defined by two indices, i and j, representing a sub-array.
The chocolate.go example is powerful because the state (i, j) represents a sub-problem on the slice choco[i:j]. This pattern of using two pointers to define a sub-array or sub-string is extremely common in DP problems, such as Longest Palindromic Subsequence, which we will see later.
For more practice, the article "Memoization and Tabulation" provides Go code for both Fibonacci and the Longest Common Subsequence (LCS) problem, which is another classic 2D DP problem where the state is defined by indices from two different input strings. You can review that resource (ID LINK) in your own time.
Conclusion
In this lesson, we made the crucial transition from identifying DP problems to solving them. We learned that memoization is a systematic, top-down technique that transforms an inefficient brute-force recursion into an optimized DP solution by caching subproblem results.
Key Takeaways:
- Top-Down Approach: Memoization follows the logic of a natural recursive solution, starting from the top (the original problem) and breaking it down.
- The 3-Step Pattern: The process is mechanical:
- Define the state and create a cache (memo).
- Check the cache at the function's entry point.
- Compute and store the result in the cache before returning.
- Intuitive and Powerful: This method is often the easiest to devise in an interview once you have a recursive solution in mind. It directly fixes the exponential complexity caused by overlapping subproblems.
- Complexity: The time complexity of a memoized solution is generally the number of unique states multiplied by the work done per state (which is often after recursive calls). The space complexity includes the memoization table and the recursion call stack.
Memoization is an incredibly powerful tool. However, it relies on recursion, which can have overhead and, in some languages, may lead to stack overflow errors for very deep recursion. In our next lesson, we will explore tabulation, a bottom-up iterative approach that solves the same problems without recursion, and we will discuss the trade-offs between the two techniques.