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