Skip to problem
←

Climbing Stairs

Easy 0 attempts

You're at the bottom of a staircase with n steps, and each move lets you go up either 1 or 2 steps at a time. Work out how many distinct sequences of moves will get you to the top.

Function contract

Implement climbStairs(n), where n is the total number of steps. Each move climbs exactly 1 or 2 steps.

Output: The number of ordered move sequences whose sum is exactly n.

Example 1

Input
n = 2
Output
2

Example 2

Input
n = 3
Output
3

Explanation: The sequences are [1,1,1], [1,2], and [2,1].

Example 3

Input
n = 5
Output
8
Constraints
  • 1 <= n <= 45

Dynamic Programming (Fibonacci)

javascript
function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) [a, b] = [b, a + b];
  return b;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript