Climbing Stairs Problem

Difficulty: Medium, Asked-in: Google, Amazon, Intel, Morgan Stanley, LinkedIn.

Key takeaway: An excellent problem to learn problem-solving using dynamic programming and application of the Fibonacci series. One can find a lot of similar DP problems asked during the coding interview.

Let’s understand the problem

There is a staircase of n steps and you can climb either 1 or 2 steps at a time. We need to count and return total number of unique ways to reach the nth stair. The order of steps matters.

Example 1

Input: n = 3, Output: 3.

Explanation: There are 3 unique ways of climbing the staircase: [1,1,1], [2,1] and [1,2].

Example 2

Input: n = 5, Output: 8.

Explanation: There are 8 unique ways of climbing the staircase: [1,1,1,1,1], [1,1,1,2], [1,1,2,1], [1,2,1,1], [2,1,1,1], [1,2,2], [2,1,2], [2,2,1].

Discussed solution approaches

  • Brute force approach using recursion
  • Using bottom-up approach of dynamic programming
  • Using the idea of Fibonacci sequence
  • Using Binet’s method of matrix exponentiation

Brute force approach  using recursion

Solution idea

This is a counting problem where we need to count all unique ways to reach the nth stair. The critical question is: how do we count all possibilities? We have two different choices at the start: we can either climb the 1st stair or the 2nd stair because we can only jump 1 or 2 steps at a time.

  • If we take 1 step from the ground, the smaller sub-problem is climbing the nth stair from the 1st stair.
  • If we take 2 steps from the ground, the smaller sub-problem is climbing the nth stair from the 2nd stair.
  • So, we can solve the given counting problem recursively by adding the solutions of the sub-problems: climbingStairs(0, n) = climbingStairs(1, n) + climbingStairs(2, n).

We can also think of it with another analogy: we can reach the nth stair from the (n - 1)th stair and the (n - 2)th stair by taking 1 and 2 steps, respectively. So the total number of ways to reach the nth stair = Total number of ways to reach the (n - 1)th stair + Total number of ways to reach the (n - 2)th stair => climbingStairs(n) = climbingStairs(n-1) + climbingStairs(n-2).

Solution pseudocode

climbingStairs(i, n)
    if i > n
        return 0

    if i == n
        return 1
    // Count ways by taking either one or two steps
    return climbingStairs(i + 1, n) + climbingStairs(i + 2, n)

countClimbStairs(n)
    return climbingStairs(0, n)

Time and space complexity analysis

Input size of the 1st subproblem = n - 1 and Input size of the 2nd subproblem = n - 2. So we write the recurrence relation of the time complexity in terms of the input size, i.e., T(n) = T(n - 1) + T(n - 2), where T(1) = 1 and T(2) = 2.

The above recurrence relation is similar to the recurrence relation of the Fibonacci sequence. So time complexity = O(2^n). But why is the time complexity in exponential? We can visualise it better using a recursion tree diagram, where we are solving the same subproblem again and again during recursion. Here is a basic example for n = 4.

climbing stairs problem recurison tree1

Space complexity = O(n), The depth of recursion tree can go up to n and recursion will allocate call stack of size O(n).

Using bottom-up approach

Solution idea and steps

We need to take care of the following steps to solve the problem using a bottom-up approach:

  • Table size and structure: There are (n+1) different subproblems with input sizes from 0 to n. So we need to take a stair[] table of size n + 1 to store the solution to these subproblems.
  • Table Initialisation: Before building the solution in a bottom-up manner, we initialize the table by using the basic version of the solution. We can get this idea from the base case of the recursive solution. stair[1] = 1, stair[2] = 2.
  • Iterative structure to fill the table: Now we define an iterative structure to fill the table. We can get this idea from the recursive structure of the recursive solution. Here is an insight: Recursion is coming top-down and solving the larger problem via the solution of smaller subproblems. In a similar but reverse fashion, we bottom-up combine smaller problems to build the solution for the larger problem.

    Total number of ways to reach the ith stair = Total number of ways to reach (i - 1)th stair + Total number of ways to reach (i - 2)th stair => stair[i] = stair[i-1] + stair[i-2].

  • Returning the final solution: After storing the results in the table, our final solution gets stored at the last index of the array, i.e., return stair[n].

Solution pseudocode

climbingStairs(n)
    if n == 0
        return 0

    if n == 1
        return 1

    stair = array of size n + 1
    stair[1] = 1
    stair[2] = 2
    // Count ways to reach each stair from the previous two stairs
    for i from 3 to n
        stair[i] = stair[i - 1] + stair[i - 2]

    return stair[n]

Time and space complexity analysis

We are running a single loop and doing constant operations at each step of the iteration, so the time complexity is O(n). The space complexity is also O(n) because we are using extra space of size n+1.

Using Fibonacci sequence

Solution idea

If we observe, their recursive structure is similar to the Fibonacci sequence. The total number of ways to reach the nth stair = nth Fibonacci number, where 1 and 2 are the first and second terms, respectively. fib(n) = fib(n-1) + fib(n-2), where fib(1) = 1 and fib(2) = 2.

Instead of using recursion or extra memory to store the solutions to subproblems, we can calculate the nth Fibonacci number in place and return it as the output.

Solution pseudocode

climbingStairs(n)
    if n == 0 or n == 1
        return n

    firstFib = 1
    secondFib = 2
      
    for i from 3 to n
        nextFib = firstFib + secondFib
        firstFib = secondFib
        secondFib = nextFib

    return secondFib

Time and space complexity analysis

We are just running a single loop and doing constant operations at each step of the iteration, so the time complexity is O(n). The space complexity is O(1) because we are only using a constant number of variables.

Using Binet’s method of matrix exponentiation

Solution idea

This is an efficient method to find the nth Fibonacci number, which uses this idea: if we multiply the matrix M = [[1,1],[1,0]] n times or calculate power(M, n), then we get the (n+1)th Fibonacci number as the element at the 0th row and 0th column, i.e., at the position (0, 0) in the final matrix.

Binet’s method of matrix exponentiation

So, we can use the same initial matrix M and return the element at index (0, 0) of Mⁿ, which is the (n + 1)th Fibonacci number. We can do this because the number of ways to reach the nth stair is equal to the (n + 1)th value of the standard Fibonacci sequence.

Solution pseudocode

countWaysToClimbStairs(n)
    M = [[1, 1],
         [1, 0]]

    finalMatrix = power(M, n)
    // Return the top-left element of M raised to nth power
    return finalMatrix[0][0]

power(X, n)
    // Initialize the result as the 2 × 2 identity matrix
    res = [[1, 0],
           [0, 1]]
    // Use exponentiation by squaring to calculate X^n
    while n > 0
        if n is odd
            res = multiply(res, X)

        X = multiply(X, X)
        n = floor(n / 2)

    return res

multiply(A, B)
    C = 2 × 2 matrix
    // Multiply the two 2 × 2 matrices
    for i from 0 to 1
        for j from 0 to 1
            C[i][j] = A[i][0] * B[0][j] +
                      A[i][1] * B[1][j]

    return C

Time and space complexity analysis

  • The time complexity of 2x2 matrix multiplication is O(1).
  • Inside the power() function, the while loop will run logn times, so the multiply() function is called logn number of times. So time complexity = O(logn) * O(1) = O(logn).
  • We are only using a constant-size extra matrix res[2][2] for the calculation of the nth power of the matrix. Therefore, space complexity = O(1)

Critical ideas to think!

  • Can we solve this problem using any other approach?
  • How do we modify the above algorithms if we can climb up to k steps at a time? What would be the recurrence relation for this?
  • How will the solution change if the order of steps you take didn’t matter? In this case, {1,1,2}, {1,2,1}, and {2,1,1} will be counted as one solution.
  • Explore the correctness proof of the matrix exponentiation approach.

Comparison of time and space complexities

  • Brute force recursive approach: Time = O(2^n), Space = O(n)
  • Using the bottom-up approach of DP: Time = O(n), Space = O(n)
  • Using the Fibonacci sequence: Time = O(n), Space = O(1)
  • Binet’s method of matrix exponentiation: Time = O(logn), Space = O(1)

Similar coding problems to practice

  • Find the number of ways to climb N stairs by taking at most k steps.
  • Find the nth Fibonacci Number.
  • Count the number of ways to reach the nth stair using steps 1, 2, or 3.
  • Consider a game where a player can score 3, 5, or 10 points in a move. Given a total score of n, find the number of ways to reach the given score.
  • Given n, count the number of ways to express n as a sum of 1, 3, and 4.
  • Count the number of paths from the top left corner to the bottom right corner of an MxN grid, where you can only move down or right.
  • Given a set of distinct integers, find all possible subsets that add up to a target sum.

If you have any queries/doubts/feedback, please write us at contact@enjoyalgorithms.com. Enjoy learning, Enjoy algorithms!

Find us on:

Self-paced Courses and Blogs