Taro Logo

Climbing Stairs

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+23
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.2K views
Topics:
Dynamic Programming

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 1:

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

Example 2:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the value of $n$? Specifically, could $n$ be zero, negative, or extremely large leading to potential integer overflow?
  2. Should we expect inputs where $n = 1$ or $n = 2$, and what is the expected output for those base cases?
  3. When the problem states 'distinct number of unique ways', does it mean different sequences of steps (e.g., [1, 2] vs [2, 1]) are counted as separate ways to reach the top?
  4. Should the return type be a standard 32-bit integer, or do we need to account for larger return values using 64-bit integers or BigInt?
  5. Are there any memory limitations or space complexity constraints I should keep in mind, such as whether an $O(1)$ space solution is strictly required?

Brute Force Solution

Approach

Imagine you are standing at the bottom of a staircase and want to reach the top by taking steps of either one or two at a time. The brute force strategy involves physically exploring every single combination of one-step and two-step hops until you reach the very top.

Here's how the algorithm would work step-by-step:

  1. Start at the bottom of the staircase.
  2. At your current position, consider your two choices: either take a single step up or take a double step up.
  3. Choose the first option, take a single step, and then repeat this entire decision-making process from your new position until you either reach the top or go past it.
  4. If you successfully reach the exact top, count that specific sequence of steps as a successful way to climb the stairs.
  5. If you go past the top, recognize that this particular path does not work and abandon it.
  6. Return to the last point where you made a choice, and now try the other option of taking a double step.
  7. Repeat this exhaustive exploration for every possible branch of choices, ensuring you test every single combination.
  8. Count up all the successful paths you found at the very end to know the total number of ways to climb the stairs.

Code Implementation

def climb_stairs_brute_force(total_stairs):
    def explore_paths(current_step):
        # Base case to count a successful path when we land exactly on the top
        if current_step == total_stairs:
            return 1
        
        # Abandon the current exploration branch if we overshoot the target
        if current_step > total_stairs:
            return 0
        
        # Exhaustively explore both single and double step choices from here
        return explore_paths(current_step + 1) + explore_paths(current_step + 2)

    return explore_paths(0)

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force approach uses a recursive decision tree where, at every step, we branch into two choices of taking either one or two steps until we reach the top. For an input size of n, this creates a binary tree of choices with a maximum depth of n, leading to approximately 2ⁿ total function calls and operations. Summing the nodes across all levels of this binary tree results in 2ⁿ⁺¹ - 1 operations, which simplifies to the exponential Big O time complexity of O(2ⁿ).
Space Complexity
O(n) – The brute force strategy described relies on exploring every combination of steps through recursive function calls, which creates a call stack in memory. The maximum depth of this recursion stack corresponds to taking only single steps, which reaches a depth of N. Therefore, the auxiliary space complexity is driven by the maximum depth of the recursion tree, resulting in linear memory usage relative to the input size N.

Optimal Solution

Approach

Instead of recalculating every possible way to reach the top, the optimal approach builds the solution from the ground up using past results. By remembering how many ways it took to reach the previous two steps, you can instantly figure out the number of ways to reach the current step.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very beginning of the staircase where there is only one way to stay put and one way to take a single step up.
  2. Shift your focus to the next step up and realize that the total ways to reach it is simply the sum of the ways to reach the two positions right behind it.
  3. Move upward one step at a time, keeping a running tally of the total ways by always adding together the results from the previous two steps you just calculated.
  4. Continue this process step by step until you reach the final top level.
  5. Return the final accumulated total as the answer, having found the solution efficiently without ever having to retrace your path or guess blindly.

Code Implementation

def climb_stairs(total_steps):    # Base cases are established since the first two steps have predetermined ways to reach them.    ways_for_step_zero = 1    ways_for_step_one = 1    # We iterate forward because each step dynamically depends strictly on the two preceding steps.    for current_step_index in range(2, total_steps + 1):        current_step_ways = ways_for_step_zero + ways_for_step_one        ways_for_step_zero = ways_for_step_one        ways_for_step_one = current_step_ways    # The final accumulated total represents the exact number of unique ways to reach the top.    return ways_for_step_one

Big(O) Analysis

Time Complexity
O(n) – To find the total ways to reach the top of an n-step staircase, we iterate from step 3 up to n exactly once, performing a constant amount of addition work at each step. The input size n directly drives this single loop of cost since we build our solution from the ground up using past results. The total operations scale linearly with n as we compute the values sequentially without backtracking. This progression results in approximately n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm tracks only a running tally of the total ways using a couple of scalar integer variables rather than allocating an auxiliary array of size N. As the input size N grows, these few persistent variables require a constant amount of extra memory regardless of the staircase height. Consequently, the memory consumption remains strictly flat without utilizing recursion stack frames or temporary lists. The total extra memory simplifies to a constant space complexity of O(1).

Edge Cases

Input n equals 1
How to Handle:
Return 1 since there is only one way to climb a single step.
Input n equals 2
How to Handle:
Return 2 because the two distinct ways are 1+1 and 2.
Input n is zero or negative
How to Handle:
Return 0 or handle as a base case since no steps are required.
Very large values of n causing integer overflow
How to Handle:
Use 64-bit integers or big integers if n exceeds standard 32-bit integer limits.
Maximum constraint n values causing performance bottlenecks in recursion
How to Handle:
Use dynamic programming with O(n) time complexity and O(1) space to avoid stack overflow and TLE.
0/75 completed