Climbing Stairs Problem – Counting Ways to Reach the Top ????♂?
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
Problem Statement
Given a staircase with n steps, determine the number of distinct ways to reach the top. You can either climb 1 step or 2 steps at a time.
Example Calculations:
Mathematical Pattern – Fibonacci Approach
At any step n, you can only arrive from step n-1 or n-2.
Thus, the total ways to reach step n is the sum of the ways to reach the previous two steps:
climbingStaircase(n) = climbingStaircase(n-1) + climbingStaircase(n-2)
const climbingStaircase = n => {
const noOfWays = [1, 2];
for (let i = 2; i < n; i++) {
noOfWays[i] = noOfWays[i - 1] + noOfWays[i - 2];
}
return noOfWays[n - 1];
};
console.log(climbingStaircase(1));
console.log(climbingStaircase(2));
console.log(climbingStaircase(3));
console.log(climbingStaircase(4));
console.log(climbingStaircase(5));
Time Complexity: O(n)