🚀 JS | ✅ Climb Stairs solution in JS

#JS#ProblemSolving#leetcode

To solve this problem

  • First we need to know the pattern of this series

    • if n = 1 n.of steps = 1

    • if n = 2 n.of steps = 2

    • if n = 3 n.of steps = 3

    • if n = 4 n.of steps = 5

    • if n = 5 n.of steps = 8

    • if n = 6 n.of steps = 13

📢notice that n.of steps of N equal n.of steps of (N-1 ) + n.of steps of (N-2)

Steps of Solution

  • if N=1 return 1

  • if N=2 retuen 2

  • if N>=3 return (n.of steps of (N-1) + n.of steps of (N-2))

✅ Javascript code implementation

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function (n) {
    if (n == 1 || n == 2) return n;

    let secondPrevSteps = 1; //n.of steps of (N-2)
    let firstPrevSteps = 2;      //n.of steps of (N-1)

    for (let i = 3; i <= n; i++) {
        let currentSteps = firstPrevSteps;
		firstPrevSteps = secondPrevSteps + firstPrevSteps;
		secondPrevSteps = currentSteps;
    }
    return firstPrevSteps;
};

🚀Runtime: 46 ms, faster than 81.34% of JavaScript online submissions for Climbing Stairs. 🚀Memory Usage: 41.4 MB, less than 81.37% of JavaScript online submissions for Climbing Stairs.

📢Follow in LinkedIn 📢Blog MG

t