Recursive Staircase problem in JavaScript

The staircase problem is a classic dynamic programming problem in computer science. Given n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 or 2 stairs at a time, and we need to count the number of ways to reach the top.

We'll write a JavaScript function that takes a number n representing the number of stairs and returns the total number of ways to climb them.

Understanding the Problem

This problem follows the Fibonacci sequence pattern. For n stairs:

  • 1 stair: 1 way (take 1 step)
  • 2 stairs: 2 ways (take 1+1 steps or take 2 steps)
  • 3 stairs: 3 ways (1+1+1, 1+2, or 2+1)
  • 4 stairs: 5 ways (combining solutions for 2 and 3 stairs)

Iterative Solution

Here's an efficient iterative approach that avoids recursion:

const recursiveStaircase = (num = 10) => {
    if (num 

89
5
377

How It Works

The algorithm uses dynamic programming with space optimization:

  1. Base cases: 0 stairs = 0 ways, 1 stair = 1 way, 2 stairs = 2 ways
  2. For each step from 3 to n, calculate ways as sum of previous two steps
  3. Use array destructuring to update the two most recent values
  4. Return the final result

Alternative Recursive Solution

Here's a simple recursive approach (less efficient for large numbers):

const recursiveStaircaseSimple = (n) => {
    if (n 

8
13

Performance Comparison

Approach Time Complexity Space Complexity Suitable for Large n?
Iterative (Optimized) O(n) O(1) Yes
Simple Recursive O(2^n) O(n) No

Conclusion

The iterative solution efficiently solves the staircase problem using dynamic programming with constant space complexity. It's ideal for large numbers of stairs, while the recursive approach is easier to understand but less efficient.

Updated on: 2026-03-15T23:19:00+05:30

720 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements