Tutorialspoint
Problem
Solution
Submissions

Climbing Stairs

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to count the number of ways to climb a staircase. You are climbing a staircase with n steps. 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: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps at once
Example 2
  • Input: n = 3
  • Output: 3
  • Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
Constraints
  • 1 ≤ n ≤ 45
  • The answer will fit within a 32-bit integer range
  • Time Complexity: O(n)
  • Space Complexity: O(1) (for the optimized solution)
NumberCognizantWalmart
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

  • This problem follows the Fibonacci sequence
  • The number of ways to reach step n is equal to the number of ways to reach step (n-1) plus the number of ways to reach step (n-2)
  • For n = 1, there's only 1 way: climb 1 step
  • For n = 2, there are 2 ways: climb 1 step + 1 step, or climb 2 steps at once
  • Use dynamic programming to avoid redundant calculations

Steps to solve by this approach:

 Step 1: Handle base cases: for n=1, return 1; for n=2, return 2.

 Step 2: Initialize variables to track the ways to climb n-1 and n-2 steps.
 Step 3: Iterate from 3 to n, calculating the total ways for each step.
 Step 4: For each step i, the number of ways equals the sum of ways for step i-1 and step i-2.
 Step 5: Update the variables for the next iteration.
 Step 6: Return the final count which represents the total number of ways to climb n steps.
 Step 7: This solution uses O(1) space and O(n) time complexity to solve the problem efficiently.

Submitted Code :