Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Dynamic Programming›Climbing Stairs
EasyDynamic Programming

Climbing Stairs

dynamic-programmingfibonacci

Problem

You are climbing a staircase with n steps. Each time you can climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Examples

Example 1

Input: n = 3

Output: 3

Explanation: Three ways: 1+1+1, 1+2, 2+1.

Constraints

  • •1 <= n <= 45

Hints

Hint 1

State the recurrence out loud before coding: to reach step n, your last move was either a 1-step from n-1, or a 2-step from n-2 — so ways(n) = ways(n-1) + ways(n-2).

Hint 2

This is structurally identical to the Fibonacci sequence — recognizing that connection is the whole insight.

Hint 3

You don't need an array to hold every intermediate value — only the last two values are ever needed at once.

Solutions

public int climbStairs(int n) {
    if (n <= 2) return n;
    int prev2 = 1, prev1 = 2; // ways(1)=1, ways(2)=2
    for (int i = 3; i <= n; i++) {
        int curr = prev1 + prev2;
        prev2 = prev1;
        prev1 = curr;
    }
    return prev1;
}
Java

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