Search code examples
pythonarraysrecursiondynamic-programmingmemoization

DP array 0th element is initialized as 1 instead of 0


I encountered the LeetCode climbStairs problem:

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?

Example:

  • Input: n = 3
  • Output: 3
  • Explanation: There are three ways to climb to the top.
    1. 1 step + 1 step + 1 step
    2. 1 step + 2 steps
    3. 2 steps + 1 step

Constraints:

  • 1 <= n <= 45

I'm wondering about the below solution (taken from https://emre.me/coding-patterns/staircase/):

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0 for x in range(n+1)]
        dp[0] = 1
        dp[1] = 1

        
        for i in range(2, n+1):
            dp[i] = dp[i-1] + dp[i-2]
        
        return dp[n]

I assume each value of the dp list denotes the number of ways one can take to reach that step.

In that case, why do we initialize the value at dp[0] to 1 instead of 0? Anyone can explain its logic?

It works fine in a recursive/array implementation if I use dp[0]=0 but with dynamic programming it only works with dp[0]=1.


Solution

  • The reasoning is that there is always at least one way to reach the top of the stairs. If the staircase has no stairs (n = 0), then there is still one way to climb the stairs, i.e. by taking no steps. Note that it is not the number of steps for reaching the top that counts (which is zero here), but the number of ways (which is still one).

    Although the code challenge states that n will be at least 1, we could extend this function to also work when n is 0. In that case we don't need dp[1] (which would be an invalid index), so we need to touch the code a little bit to make that work. For instance, we could naively foresee one more element in the dp list:

            dp = [0 for x in range(n+2)]
    

    Now you can call the function with n equal to 0 and it will return 1, which is correct, and is the value at dp[0]. Again, the number of ways to climb a staircase that has no stairs is one (not zero).