Skip to main content

Welcome to a Grasp lesson

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

Lesson 16

1D DP for Sequence Problems

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

Introduction

Welcome back! In our previous lessons, you've built a solid foundation in Dynamic Programming. We identified its core characteristics (optimal substructure and overlapping subproblems), learned the intuitive top-down approach with memoization, and then mastered the systematic process of converting it to the often more performant bottom-up (tabulation) approach.

This lesson is where we put that theory into practice. Our goal is to apply 1D DP to solve foundational sequence problems. These problems, specifically Climbing Stairs and House Robber, are canonical for a reason: they represent two fundamental patterns that appear repeatedly in more complex DP challenges. Mastering them is a non-negotiable step in preparing for senior-level interviews.

For each problem, we will follow the full progression of analysis, from a brute-force recursion to a space-optimized bottom-up solution. This mirrors the ideal thought process in an interview, demonstrating not just a correct answer but a deep understanding of trade-offs and optimization, which is expected at the Staff+ level.

1D Dynamic Programming Progression in Coding Interviews
This flowchart illustrates the typical path to mastering a DP problem: from the initial recursive insight to the fully optimized solution. We will follow this path for both problems in this lesson.

1D DP Pattern 1: Counting Ways (Climbing Stairs)

The first pattern we'll explore involves counting the number of ways to reach a certain state. The classic example is the "Climbing Stairs" problem.

The problem is stated as follows: You are climbing a staircase. It takes n steps to reach the top. Each time, you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Let's begin by reading a detailed walkthrough of this problem, which covers the logic from identifying the base cases to implementing both top-down and bottom-up solutions.

Mastering Dynamic Programming

The article 'Mastering Dynamic Programming' provides an excellent, clear explanation of the Climbing Stairs problem. It will guide us in deriving the recurrence relation and exploring different implementation approaches.

Please read the section 'Example 1: Climbing Stairs'. Focus on how the problem is broken down: identifying the base cases (for n=1 and n=2) and then deriving the general recurrence relation. Pay attention to the visualization of overlapping subproblems.

From Recurrence to Optimized Solution

As the article highlighted, the number of ways to reach step n is the sum of the ways to reach step n-1 (and taking one step) and the ways to reach step n-2 (and taking two steps).

This gives us the famous Fibonacci-like recurrence relation:

Climbing Stairs Dynamic Programming Visualization
This image visually represents the problem and its core recurrence relation, linking it directly to the Fibonacci sequence.

The following video provides a dynamic visualization of this process, from the inefficient recursive solution to the fully optimized one.

Climbing Stairs - Dynamic Programming - Leetcode 70 - Python

This video from NeetCode will walk us through the entire thought process for Climbing Stairs, from the initial brute-force recursion to the final O(1) space solution.

Please watch from 03:42 to 16:40. The video is broken down into four key parts that align with our learning progression: Brute-Force Recursion (03:42 - 08:00): Understand the decision tree and its exponential complexity. Memoization (08:00 - 10:56): See how caching prunes the decision tree. Bottom-Up Tabulation (10:56 - 15:13): Observe the conversion to an iterative approach. Space Optimization (15:13 - 16:40): This is the key insight. Notice that to compute the current step, we only need the results of the previous two steps.

Go Implementation (Space-Optimized)

As demonstrated in the video, since the calculation for dp[i] only depends on dp[i-1] and dp[i-2], we don't need to store the entire DP array. We can achieve the solution with space complexity by only keeping track of the last two values.

Here is an idiomatic Go implementation of the space-optimized bottom-up approach.

package main

// climbStairs calculates the number of distinct ways to climb n stairs.
// It uses a bottom-up dynamic programming approach with O(1) space.
func climbStairs(n int) int {
    if n <= 2 {
        return n
    }

    // 'one' represents the number of ways to reach the previous step (i-1).
    // 'two' represents the number of ways to reach the step before that (i-2).
    // We initialize them for the base case of n=2.
    // To reach step 2, there's 1 way from step 1 (one=1), and 1 way from step 0 (two=1).
    one, two := 1, 1

    // We iterate from step 3 up to n.
    for i := 2; i < n; i++ {
        // The number of ways to reach the current step 'i' is ways(i-1) + ways(i-2).
        // 'temp' stores the old value of 'one' (which is ways(i-1)).
        temp := one
        // The new 'one' becomes the number of ways to reach the current step.
        one = one + two
        // 'two' is updated to the old 'one'.
        two = temp
    }
    
    // After the loop, 'one' + 'two' will be the number of ways to reach step n.
    return one + two
}

Note: A more compact way to write the loop body in Go is one, two = one+two, one, which swaps the values without a temporary variable.


1D DP Pattern 2: Optimization (House Robber)

The second fundamental pattern involves making a sequence of choices to achieve a maximum (or minimum) value. The "House Robber" problem is the quintessential example.

The problem: You are a robber planning to rob houses along a street. Each house has a certain amount of money. The only constraint is that you cannot rob adjacent houses. Given an array of integers representing the money in each house, what is the maximum amount you can rob?

This problem introduces the powerful "pick vs. not-pick" decision-making process at the core of many optimization-focused DP problems.

Deriving the Recurrence

For each house i, you have two choices:

  1. Rob house i: If you do, you gain nums[i] money. However, you cannot rob house i-1. The maximum money you could have up to this point is nums[i] plus the maximum you could have robbed up to house i-2.
    • rob_i = nums[i] + max_money(i-2)
  2. Do not rob house i: If you skip it, you gain no money from this house. The maximum money you can have is simply the maximum you could have robbed up to house i-1.
    • skip_i = max_money(i-1)

The optimal solution for house i is the maximum of these two choices. This gives us the recurrence:

Let's watch a detailed video that builds this intuition and walks through the implementation.

DP 5. Maximum Sum of Non-Adjacent Elements | House Robber | 1-D | DP on Subsequences

The channel 'take U forward' provides a very clear, step-by-step analysis of the House Robber problem, which is excellent for understanding the 'pick vs. non-pick' logic.

Please watch the following segments. This video provides a comprehensive look from every angle. Problem and Recurrence (00:33 - 10:35): Focus on how the 'pick' and 'non-pick' options translate into the recurrence relation. Memoization (10:35 - 18:34): This section confirms our understanding of the top-down approach by visualizing the recursion tree and identifying overlapping subproblems. Tabulation (18:34 - 25:09): See how the recurrence is translated into a bottom-up iterative solution. Space Optimization (25:09 - 30:45): Just like with Climbing Stairs, notice that the current state only depends on the previous two. This part clearly explains how to reduce space complexity to O(1).

You can also review this concept in the Mastering Dynamic Programming article (LINK) under the section "Example 2: House Robber". It provides a concise written summary of the same logic.

Go Implementation (Space-Optimized)

The logic is very similar to the space optimization for Climbing Stairs. We only need to track the results for i-1 and i-2 to compute the result for i.

Here is the space-optimized Go solution:

package main

import "math"

// rob calculates the maximum amount of money that can be robbed from a row of houses
// without robbing adjacent ones. It uses a bottom-up DP approach with O(1) space.
func rob(nums []int) int {
    if len(nums) == 0 {
        return 0
    }

    // 'prev1' holds the max money robbed up to house i-1.
    // 'prev2' holds the max money robbed up to house i-2.
    var prev1, prev2 int

    for _, num := range nums {
        // 'currentMax' will be the max money robbed up to the current house.
        // It's the maximum of two choices:
        // 1. Rob the current house (num) + the max from two houses ago (prev2).
        // 2. Don't rob the current house, so take the max from the previous house (prev1).
        currentMax := math.Max(float64(num + prev2), float64(prev1))

        // Update pointers for the next iteration.
        // The old 'prev1' becomes the new 'prev2'.
        prev2 = prev1
        // The 'currentMax' becomes the new 'prev1'.
        prev1 = int(currentMax)
    }

    // After iterating through all houses, prev1 holds the global maximum.
    return prev1
}

Conclusion

In this lesson, you've applied your DP knowledge to two foundational 1D problems, moving from high-level recurrence relations all the way to space-optimized Go code. This full-stack understanding is precisely what's expected in a senior-level interview.

Key Takeaways:

  • Two Core 1D Patterns: You've learned to identify and solve the two main types of 1D DP problems:
    • Counting Ways (Climbing Stairs): Characterized by an additive recurrence relation, often Fibonacci-like (dp[i] = dp[i-1] + ...).
    • Optimization (House Robber): Characterized by a "pick vs. not-pick" decision, using max or min in the recurrence (dp[i] = max(pick, not_pick)).
  • Space Optimization is Key: For both patterns, we saw that if the current state dp[i] depends only on a fixed number of preceding states (like dp[i-1] and dp[i-2]), we can optimize space from to . Being able to identify and implement this is a crucial signal of a strong candidate.
  • Systematic Approach: The process of defining a recurrence, implementing it with tabulation, and then optimizing for space is a reliable and powerful framework for tackling a wide range of DP problems.

In our next lesson, "Solve simple 2D DP problems on grids (e.g., Unique Paths, Minimum Path Sum)," we will see how these exact same patterns extend from a 1D sequence to a 2D grid. The "Climbing Stairs" counting pattern will evolve into "Unique Paths," and the "House Robber" optimization pattern will evolve into "Minimum Path Sum." Your work today has built the perfect foundation for this next step.