The problem follows a pattern where the number of ways to reach step n is the sum of the ways to reach step -1 and step -2, which is exactly how the Fibonacci series is constructed.
Key takeaways:
Recognize the Fibonacci pattern: The Climbing Stairs problem follows a recurrence relation similar to the Fibonacci sequence, where each step is the sum of the previous two steps.
Dynamic programming for efficiency: The naive recursive solution for Climbing Stairs explores all possible ways to reach the top, resulting in repeated calculations and an exponential time complexity of
. Using dynamic programming reduces this to by storing and reusing subproblem results. Interview preparation tip: Practice Climbing Stairs and similar dynamic programming problems to build the skill of breaking down complex problems—essential in coding interviews and real-world optimization tasks.
Climbing Stairs is one of the frequently asked coding question by top tech companies like
The Climbing Stairs problem is an important one to practice for technical interviews because it covers skills that companies like Meta, Amazon, Apple, Google, and Microsoft (MAANG) often test. This problem introduces you to dynamic programming, a key technique for solving tricky and complex coding problems more efficiently. It also builds your ability to recognize patterns, like the Fibonacci sequence, which comes up often in coding challenges.
The climbing stairs is a simple, but really valuable for interview prep. By practicing this problem, you’ll gain confidence and be better prepared for tougher, more advanced problems in technical interviews. Let's walk through the solution to this problem, covering the algorithm steps, code, and a time and space complexity analysis.
You are climbing a staircase with
Constraints:
You can only take 1 step or 2 steps at a time.
Let's look at the following examples to better understand the problem.
Now that we understand the problem, let’s test our knowledge by finding the total number of ways to reach the top when
Intuition behind the solution:
We'll start with discussing a few examples.
For a staircase with 1 step,
For a staircase with 2 steps,
1 step twice, i.e., 1 step + 1 step
2 steps at once, i.e., 2 steps
For a staircase with 3 steps,
1 step once and 2 steps once, i.e., 1 step + 2 steps
1 step thrice, i.e., 1 step + 1 step + 1 step
2 steps once and 1 step once, i.e., 2 steps + 1 step
Now, for
Number of ways for
Similarly, for
Number of ways for
This is not a coincidence, but a pattern that underlies—for every
Do you see what pattern this is? Yes, it’s the well-known
Let's look at the following illustration for a better understanding.
In this solution, we use the iterative dynamic programming approach—bottom-up. In a bottom-up approach, we start solving the smallest subproblems first and use their solutions to build up to the larger problem. In this case, the code starts with the number of ways to reach the first two steps and then iteratively calculates the number of ways for higher steps until it reaches
Instead of calculating the ways to reach each step from scratch, the code builds on the solutions for earlier steps, which is a key idea in dynamic programming. By storing just the last two results, the ways to reach
Now, let's go over the algorithm steps:
Create and initialize two variables, ways_n_1
and ways_n_2
, to 1. The first one represents the number of ways to reach the
Use a loop that goes from 2 to
Calculate the number of ways to reach the current step, current_number_of_ways
, by adding ways_n_1
and ways_n_2
.
Update the values of ways_n_1
and ways_n_2
.
Assign ways_n_2
the value of ways_n_1
.
Assign ways_n_1
the value of current_number_of_ways
.
Once the loop is finished, ways_n_1
will hold the total number of ways to reach the top of the staircase with
Let’s look at the Python code for the above algorithm that implements the Fibonacci series to calculate the total number of ways to reach the top.
def climbing_stairs(n):# Stores the total ways to climb n - 1 stepsways_n_1 = 1# Stores the total ways to climb n - 2 stepsways_n_2 = 1# Loop over the total single steps needed to reach the top for n stepsfor _ in range(2, n + 1):# Current_number_of_ways stores the sum of the previous two termscurrent_number_of_ways = ways_n_1 + ways_n_2# Update the value of ways_n_2 to ways_n_1 and ways_n_1 to current_number_of_waysways_n_2 = ways_n_1ways_n_1 = current_number_of_ways# In the end, ways_n_1 will store the total steps to reach the top on n stairsreturn ways_n_1# Driver codedef main():test_cases = [1, 2, 3, 4, 5, 6, 7, 8] # List of different values of n to testfor n in test_cases:result = climbing_stairs(n)print(f"Total number of ways for n = {n} : {result}")print("-"*100)if __name__ == "__main__":main()
The loop runs from 2 to
We only use a fixed amount of space for the variables ways_n_1
, ways_n_2
, and current_number_of_ways
, regardless of the input size
Some coding problems that are similar to the Climbing Stairs problem, often involving dynamic programming or recursive approaches:
Unique Paths: Given a grid of
Coin Change: Given a set of coin denominations and a total amount, determine the number of different ways to make that amount using the given coins.
House Robber: You are a burglar trying to rob houses arranged in a circle. If you rob two adjacent houses, you trigger an alarm. Find the maximum amount of money you can rob without triggering the alarm.
Decode Ways: Given a string containing digits, determine the total number of ways to decode it where '1' maps to 'A', '2' maps to 'B', and so on up to '26' mapping to 'Z'.
Longest Increasing Subsequence: Given an array of integers, find the length of the longest increasing subsequence.
If you're looking to practice more of these coding problems, Educative offers a comprehensive course dedicated to dynamic programming coding problems. For every coding problem, it has covered three solution approaches—the naive, the top-down, and the bottom-up—along with their complexity analysis. You can find the course [here].
On that note, take a look at some other Answers that cover solutions to frequently asked LeetCode problems in detail:
If you think you're done preparing for the technical interview, try attempting Educative's AI-empowered mock interviews. Mock interviews, in general, help you build confidence, improve your problem-solving skills, and identify areas where you can improve before the actual interview.
Haven’t found what you were looking for? Contact Us
Free Resources