Climbing Stairs - Problem

Imagine you're at the bottom of a staircase with exactly n steps leading to the top. You want to reach the top, but there's a catch - you can only take 1 step or 2 steps at a time!

Your goal is to determine how many different ways you can climb to the top of the staircase.

Example: If there are 3 steps, you could climb them as:

  • 1 step + 1 step + 1 step
  • 1 step + 2 steps
  • 2 steps + 1 step

That's 3 different ways total!

Input: An integer n representing the number of steps
Output: An integer representing the number of distinct ways to reach the top

Input & Output

example_1.py โ€” Basic case with 2 steps
$ Input: n = 2
โ€บ Output: 2
๐Ÿ’ก Note: There are two ways to climb to the top: 1. Take 1 step + 1 step, 2. Take 2 steps at once
example_2.py โ€” Medium case with 3 steps
$ Input: n = 3
โ€บ Output: 3
๐Ÿ’ก Note: There are three ways: 1. Take 1+1+1 steps, 2. Take 1+2 steps, 3. Take 2+1 steps
example_3.py โ€” Edge case with 1 step
$ Input: n = 1
โ€บ Output: 1
๐Ÿ’ก Note: There is only one way to reach the top: take 1 step

Visualization

Tap to expand
๐ŸŽฎ The Staircase GameStep 01 wayStep 11 wayStep 22 waysStep 33 waysStep 45 waysStep 58 ways+1+2Jump Options:Small Jump (+1 step)Big Jump (+2 steps)Fibonacci Pattern Discovered!1, 1, 2, 3, 5, 8, 13, 21, 34...Each number = sum of previous two
Understanding the Visualization
1
Recognize the Pattern
To reach step n, you must come from either step (n-1) or step (n-2)
2
Count Combinations
Total ways to reach step n = ways to reach (n-1) + ways to reach (n-2)
3
Fibonacci Connection
This creates the famous Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13...
Key Takeaway
๐ŸŽฏ Key Insight: The climbing stairs problem is the Fibonacci sequence in disguise! Each step count equals the sum of the two previous step counts, leading to an elegant O(n) time, O(1) space solution.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single loop from 2 to n, each iteration takes constant time

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses two variables regardless of input size

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 45
  • Integer overflow: The answer will fit in a 32-bit integer
  • The problem is guaranteed to have a valid solution
Asked in
Amazon 42 Google 38 Microsoft 31 Meta 24 Apple 18
89.2K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen