Climbing Stairs - Problem

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?

Note: Given n will be a positive integer.

Input & Output

Example 1 — Small Staircase
$ Input: n = 2
Output: 2
💡 Note: There are two ways to climb to the top: 1. 1 step + 1 step, 2. 2 steps
Example 2 — Medium Staircase
$ Input: n = 3
Output: 3
💡 Note: There are three ways: 1. 1+1+1 steps, 2. 1+2 steps, 3. 2+1 steps
Example 3 — Single Step
$ Input: n = 1
Output: 1
💡 Note: Only one way to climb 1 step: take 1 step

Constraints

  • 1 ≤ n ≤ 45

Visualization

Tap to expand
Climbing Stairs - Space-Optimized DP INPUT TOP Step 1 Start n = 2 (2 steps to climb) Can climb 1 or 2 steps at a time ALGORITHM STEPS 1 Initialize prev1=1, prev2=1 2 Loop i=2 to n curr = prev1 + prev2 3 Update vars prev2=prev1, prev1=curr 4 Return prev1 Final answer Trace for n=2: prev2=1 prev1=1 curr=2 i=2: curr = 1 + 1 = 2 O(n) time, O(1) space FINAL RESULT 2 Distinct Ways: Way 1: 1+1 steps +1 +1 Way 2: 2 steps +2 Output: 2 OK - 2 distinct ways found Key Insight: This is the Fibonacci sequence! Ways to reach step n = ways to reach (n-1) + ways to reach (n-2). Space-optimized DP uses only 2 variables instead of an array, achieving O(1) space complexity. f(n) = f(n-1) + f(n-2) where f(1)=1, f(2)=2 ---> follows Fibonacci pattern. TutorialsPoint - Climbing Stairs | Space-Optimized DP Approach
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
311.6K Views
Very High Frequency
~15 min Avg. Time
8.4K 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