How to implement backtracking for a climbing stairs practice in JavaScript?

In the given problem statement we are asked to implement backtracking for a climbing stairs practice with the help of JavaScript functionalities. In data structures, backtracking is popularly known to explore all possible solutions. We can solve this problem with the help of a backtracking algorithm.

What is the Backtracking Technique?

Backtracking is a well-known algorithmic technique, which is basically used to solve problem statements that include searching for all possible solutions. It is based on a depth-first strategy and is used in combination with a recursive method.

The basic ideology for this technique is to explore all the paths in a search environment by incrementally making a candidate solution and testing if it satisfies the constraints. This process is repeated until all possible paths give a valid solution.

The key components of this technique are:

  • Candidate solution - The partial solution that is being constructed incrementally.

  • Constraints - The rules that the candidate solution must satisfy to be considered valid.

  • Feasible solution - A candidate solution that satisfies all the constraints.

  • Backtracking - The process of leaving a candidate solution that violates a constraint and returning to the previous decision point to explore a different path.

Problem Understanding

The climbing stairs problem is a classic example that can be solved using backtracking. Given a staircase of n steps and the possibility to climb either 1 or 2 steps at a time, we need to find the total number of distinct ways to climb to the top.

0 1 2 3 +1 +2 +1 +2 From each step: +1 or +2

Algorithm

Step 1: Define a function climbStairs(n) that takes an integer n as an argument representing the number of stairs.

Step 2: Create a helper function backtrack(step) that takes the current step position as parameter.

Step 3: Check if the current step exceeds n (invalid path) - return immediately.

Step 4: If the current step equals n, we've reached the top - increment the count.

Step 5: Recursively explore both possibilities: step + 1 and step + 2.

Step 6: Return the total count of valid paths.

Example

// Function to calculate climbing stairs using backtracking
function climbStairs(n) {
    let count = 0;
    
    // Define backtrack helper function
    function backtrack(step) {
        // Base case: exceeded target
        if (step > n) {
            return;
        }
        
        // Base case: reached target
        if (step === n) {
            count++;
            return;
        }
        
        // Explore both possibilities
        backtrack(step + 1);  // Take 1 step
        backtrack(step + 2);  // Take 2 steps
    }
    
    backtrack(0);
    return count;
}

// Test with different values
console.log("Ways to climb 3 stairs:", climbStairs(3));
console.log("Ways to climb 4 stairs:", climbStairs(4));
console.log("Ways to climb 5 stairs:", climbStairs(5));
Ways to climb 3 stairs: 3
Ways to climb 4 stairs: 5
Ways to climb 5 stairs: 8

How It Works

For n = 3, the algorithm explores these paths:

  • Path 1: 0 ? 1 ? 2 ? 3 (three 1-steps)

  • Path 2: 0 ? 1 ? 3 (1-step + 2-step)

  • Path 3: 0 ? 2 ? 3 (2-step + 1-step)

Each valid path increments the counter, resulting in 3 total ways.

Optimized Version with Path Tracking

function climbStairsWithPaths(n) {
    const allPaths = [];
    
    function backtrack(step, currentPath) {
        if (step > n) return;
        
        if (step === n) {
            allPaths.push([...currentPath]);
            return;
        }
        
        // Try 1 step
        currentPath.push(1);
        backtrack(step + 1, currentPath);
        currentPath.pop();
        
        // Try 2 steps
        currentPath.push(2);
        backtrack(step + 2, currentPath);
        currentPath.pop();
    }
    
    backtrack(0, []);
    return allPaths;
}

const paths = climbStairsWithPaths(4);
console.log("All paths for 4 stairs:");
paths.forEach((path, index) => {
    console.log(`Path ${index + 1}: [${path.join(', ')}]`);
});
console.log(`Total ways: ${paths.length}`);
All paths for 4 stairs:
Path 1: [1, 1, 1, 1]
Path 2: [1, 1, 2]
Path 3: [1, 2, 1]
Path 4: [2, 1, 1]
Path 5: [2, 2]
Total ways: 5

Complexity Analysis

Time Complexity: O(2^n) - At each step, we have 2 choices (1 or 2 steps), creating a binary tree of height n.

Space Complexity: O(n) - The recursion stack can go up to depth n in the worst case.

This exponential time complexity can be optimized using dynamic programming to O(n), but backtracking helps us understand all possible solution paths.

Conclusion

Backtracking for climbing stairs demonstrates how to explore all possible solutions systematically. While the O(2^n) complexity makes it inefficient for large inputs, it provides excellent insight into the problem structure and solution space exploration.

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

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements