Tutorialspoint
Problem
Solution
Submissions

Climbing Stairs

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a Java program to solve the 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?

Example 1
  • Input: n = 2
  • Output: 2
  • Explanation:
    • Step 1: Identify that this is a dynamic programming problem where each step depends on previous steps.
    • Step 2: For n = 2, we can either take two 1-step moves or one 2-step move.
    • Step 3: The two distinct ways are: [1+1] and [2].
    • Step 4: Return 2 as the total number of ways to climb the staircase.
Example 2
  • Input: n = 3
  • Output: 3
  • Explanation:
    • Step 1: Apply the same dynamic programming approach for n = 3.
    • Step 2: For n = 3, we can take three 1-step moves, or one 1-step and one 2-step move in different orders.
    • Step 3: The three distinct ways are: [1+1+1], [1+2], and [2+1].
    • Step 4: Return 3 as the total number of ways to climb the staircase.
Constraints
  • 1 ≤ n ≤ 45
  • You must solve this efficiently to handle large inputs
  • Time Complexity: O(n)
  • Space Complexity: O(1)
NumberPwCZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Notice that this problem follows the Fibonacci sequence pattern
  • The number of ways to reach step n is the sum of ways to reach step n-1 and step n-2
  • Use dynamic programming to avoid redundant calculations
  • You only need to keep track of the previous two values, not the entire array
  • Initialize base cases for steps 1 and 2, then build up to n

Steps to solve by this approach:

 Step 1: Handle base cases - if n is 1 or 2, return n (1 way for 1 step, 2 ways for 2 steps).
 Step 2: Initialize variables to keep track of the number of ways for the previous two steps: prev1 = 1 (for 1 step) and prev2 = 2 (for 2 steps).
 Step 3: Use a loop to calculate the number of ways for each step from 3 to n.
 Step 4: For each step i, the number of ways is the sum of ways for step i-1 and step i-2.
 Step 5: Update prev1 and prev2 for the next iteration.
 Step 6: After completing the loop, prev2 contains the number of ways to climb n steps.
 Step 7: Time complexity is O(n) and space complexity is O(1) since we only use a constant amount of extra space.

Submitted Code :