Skip to main content

Welcome to a Grasp lesson

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

Lesson 18

Optimizing Space in Dynamic Programming

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

Introduction

In our last lesson, we extended our 1D DP knowledge to solve 2D grid problems like Unique Paths and Minimum Path Sum. In doing so, we got a sneak peek at today's topic by optimizing the space complexity of our grid solutions from down to .

Today, we will formalize and generalize this crucial skill. The learning outcome for this lesson is to optimize space complexity in DP solutions. This isn't just a minor optimization; in an interview for a Staff-level role, demonstrating this ability shows a deep understanding of a problem's dependency structure and an awareness of resource constraints, which are vital in real-world system design.

We'll dissect two primary patterns of space optimization:

  1. 2D to 1D Optimization: Reducing space from to or , common in grid and sequence comparison problems.
  2. 1D to Constant Optimization: Reducing space from to , applicable when a state only depends on a fixed number of preceding states.

By the end of this lesson, you'll be able to identify when these optimizations are possible and confidently implement them in Go.


1. Pattern 1: From 2D Array to 1D Array ()

As we saw with Unique Paths, this optimization is possible when the calculation for a cell dp[i][j] depends only on values from the previous row (i.e., i-1) and/or the current row (i). If you don't need to look back two or more rows, you don't need to store the entire 2D table.

Let's re-examine the Unique Paths problem through this specific lens.

Recurrence Relation: dp[i][j] = dp[i-1][j] + dp[i][j-1]

To calculate dp[i][j], we need:

  • dp[i-1][j]: The value from the cell directly above (in the previous row).
  • dp[i][j-1]: The value from the cell to the left (in the current row).

This dependency is key. To see exactly how this allows for optimization, let's watch a segment of the video from our last lesson, focusing purely on the space optimization logic.

DP 8. Grid Unique Paths | Learn Everything about DP on Grids | ALL TECHNIQUES 🔥

Let's revisit the 'take U forward' video on Unique Paths. This time, focus exclusively on the logic for space optimization, where the 2D DP table is condensed into a 1D array.

Please watch the segment from 32:32 to 41:28. Pay close attention to how a previous array (representing row i-1) is used to compute a current array (representing row i), and how this ultimately gets simplified into a single array that's updated in place.

A Deeper Look: The "Right-to-Left" Nuance

The method shown in the video works perfectly for problems like Unique Paths. However, there's a subtle but critical detail that distinguishes a good candidate from a great one. The direction of the inner loop matters depending on the exact recurrence.

Consider the classic 0/1 Knapsack problem (which we will cover in detail later). Its recurrence looks something like this:
dp[i][j] = max(dp[i-1][j], value[i] + dp[i-1][j - weight[i]])

Notice that to compute dp[i][j], we need values from the previous row i-1 at columns j and j - weight[i]. If we use a single 1D array dp and iterate from left to right, when we compute dp[j], we might use a value dp[j - weight[i]] that has already been updated in this same pass. This is incorrect, as we need the value from the previous row.

The following article explains this insight beautifully.

Optimizing the Knapsack Problem dynamic programming solution ...

This article, 'Optimizing the Knapsack Problem', provides one of the clearest explanations for why the inner loop's direction is so important when optimizing a 2D DP table to a single 1D array.

Please read the sections 'Optimizing for Space: Step 1', 'Optimizing for Space: Step 2', and especially the subsection 'Left to Right, or Right to Left?'. This will solidify your understanding of: Why you only need to maintain the previous row's data. How you can optimize from two 1D arrays to a single 1D array. The critical insight about iterating from right to left to avoid using prematurely updated values.

This "right-to-left" iteration is a powerful Staff-level talking point. It demonstrates that you're not just applying a memorized pattern but are deeply reasoning about data dependencies and potential race conditions within your own algorithm.


2. Pattern 2: From 1D Array to Constant Space ()

This second optimization pattern is possible when the calculation for dp[i] depends only on a fixed number of previous states, such as dp[i-1] and dp[i-2]. If the state transition has a fixed "look-back" window, you only need variables to hold the states within that window, not the entire DP array.

Canonical Example: Fibonacci Sequence

The Fibonacci sequence is the simplest illustration of this.
Recurrence Relation: fib(i) = fib(i-1) + fib(i-2)

To compute the i-th number, you only need the two preceding numbers. You don't need the entire sequence up to i. This allows for a trivial O(1) space solution.

This concept is explained well in the following article, which also provides a clean Go implementation.

Mastering Fibonacci Sequence: Advanced Dynamic Programming in ...

This article from SesameDisk provides a concise Go implementation for calculating Fibonacci numbers iteratively, which naturally leads to an O(1) space solution.

Please read the sections 'Using Iteration Over Recursion' and 'Optimizing Space Complexity'. Notice how the Go code uses just two variables, a and b, to keep track of the last two numbers in the sequence, perfectly demonstrating the O(N) to O(1) optimization.

The Go code snippet from the article is a model of clarity:

// fib calculates the n-th Fibonacci number with O(1) space.
func fib(n int) int {
    if n < 2 {
        return n
    }
    // a and b hold the two previous Fibonacci numbers.
    a, b := 0, 1
    for i := 2; i <= n; i++ {
        // The new 'b' is the sum of the old 'a' and 'b'.
        // The new 'a' is the old 'b'.
        a, b = b, a+b
    }
    return b
}

Interview-Relevant Example: House Robber

A more practical and common interview problem that uses this pattern is House Robber, which we've seen before.

Recurrence Relation: rob(i) = max(nums[i] + rob(i-2), rob(i-1))

Here again, the decision at house i depends only on the optimal solutions at houses i-1 and i-2. We don't need the entire dp array. We can solve this with just two variables tracking the maximum money robbed up to the last two houses.

Let's see how this is done.

House Robber - Leetcode 198 - Python Dynamic Programming

The NeetCode video on House Robber has an excellent explanation of the final O(1) space optimization.

Please watch the clip from 07:58 to 10:02. The presenter clearly explains how to use two variables (named rob1 and rob2) to represent the dp[i-2] and dp[i-1] states and iteratively calculate the solution.

Inspired by that logic, here is what a clean, space-optimized Go solution for House Robber looks like. We can use two variables, let's call them robNext and robNextPlusOne, to track the maximums as we iterate backwards through the array, which can be a bit more intuitive for this problem's recurrence.

// houseRobber calculates the maximum amount of money that can be robbed
// with O(1) space complexity.
func houseRobber(nums []int) int {
    // robNext represents the max money that can be robbed from house i+1 onwards.
    // robNextPlusOne represents the max money that can be robbed from house i+2 onwards.
    // Initialize to 0, representing the case when there are no more houses.
    robNext, robNextPlusOne := 0, 0

    // Iterate backwards from the end of the array.
    for i := len(nums) - 1; i >= 0; i-- {
        // For the current house 'i', we have two choices:
        // 1. Rob this house (nums[i]) + the max from house i+2 onwards (robNextPlusOne).
        // 2. Don't rob this house, and take the max from house i+1 onwards (robNext).
        currentMax := max(nums[i]+robNextPlusOne, robNext)
        
        // Update the pointers for the next iteration (i-1).
        // The old robNext becomes the new robNextPlusOne.
        // The newly calculated currentMax becomes the new robNext.
        robNextPlusOne = robNext
        robNext = currentMax
    }

    // After the loop, robNext holds the answer for the whole array (from index 0 onwards).
    return robNext
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

This implementation effectively uses two variables to stand in for dp[i-1] and dp[i-2], achieving the desired O(1) space complexity.


Conclusion

Today we demystified space optimization in dynamic programming, elevating it from a "trick" to a principled technique based on analyzing dependency structures.

Key Takeaways:

  • Analyze the Recurrence: The possibility of space optimization is determined entirely by the dependencies in your DP recurrence relation.
  • 2D to 1D (O(NM) -> O(N)): This is possible when dp[i][j] only depends on the previous (i-1) and/or current (i) rows.
    • Staff-Level Insight: For recurrences like Knapsack's, where dependencies are on dp[i-1], you must iterate the inner loop right-to-left when using a single 1D array to preserve the integrity of the previous row's data.
  • 1D to Constant (O(N) -> O(1)): This is possible when dp[i] depends on a fixed number of preceding states (e.g., dp[i-1], dp[i-2]). You only need variables to store the states in this "look-back" window.

Mastering these techniques is a significant step in your DP journey. You can now not only solve a problem but also refine your solution to be highly efficient in both time and space.

Preview of the Next Lesson:
With a solid grasp of the foundational mechanics—memoization, tabulation, and space optimization—we are now ready to tackle canonical DP problem patterns. In our next lesson, we will begin Module 4, "Core Dynamic Programming Patterns," by learning to solve unbounded choice problems using DP, such as Coin Change and Rod Cutting. We'll see how the tools you've just sharpened apply to problems where you can use an item an unlimited number of times.