DSA AnimatorREVISION VIDEOS
← Back to problems
New

Climbing Stairs — LeetCode 70 video explanation

You climb a staircase with n steps, taking either 1 or 2 steps at a time. Count the number of distinct ways to reach the top.

Loading videos…

DSA Animator › DSA Revision › Dynamic Programming › Climbing Stairs

Key moments in the Climbing Stairs video

0:04Problem0:13Example0:21Brute force0:30Key idea0:52Dry run1:10Code1:23Takeaway

What you will learn

Remember: ask where the last move came from. The recurrence is the sum of the ways into the previous states. The video solves Climbing Stairs (LeetCode 70, Easy) with the 1D DP pattern from the Dynamic Programming topic, and you can replay every step in the interactive Climbing Stairs animation.

Climbing Stairs video transcript

Problem

You climb a staircase with n steps, taking either 1 or 2 steps at a time. Count the number of distinct ways to reach the top.

Example

For n equal to 5, there are 8 ways. For n equal to 3, the 3 ways are 1 1 1, then 1 2, then 2 1.

Brute force

Listing every sequence of 1 and 2 steps grows exponentially. But the count for each step can be built from smaller counts.

Key idea

Think about the very last move to step i. Either you came from step i minus 1 with a single step, or from step i minus 2 with a double step. So ways of i equals ways of i minus 1 plus ways of i minus 2. The base cases are 1 way to reach step 1, and 2 ways to reach step 2. It is the Fibonacci pattern in disguise.

Dry run

Step 1 has 1 way, and step 2 has 2 ways. Step 3 has 2 plus 1, which is 3 ways. Step 4 has 3 plus 2, which is 5 ways. Step 5 has 5 plus 3, which is 8 ways. So there are 8 ways to climb 5 steps.

Code

In code, return n when n is at most 2. Keep the counts for the previous two steps. Loop from 3 to n, adding them and shifting forward. It's O of n time and O of 1 space.

Takeaway

Remember: ask where the last move came from. The recurrence is the sum of the ways into the previous states.

More Dynamic Programming revision videos

← All 185 DSA revision videos