Start learning free

LESSON 324 OF 344 · DYNAMIC PROGRAMMING

Min Cost Climbing Stairs - JavaScript Solution with O(n) Time Complexity

Practice O(n) Read the full explanation

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top floor, given that you can either start from the step with index 0 or the step with index 1.

                             ___________
                        ___ | Final Step
                   ___ | 20
             ___ | 15
__________ | 10
First Step

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Note:

  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].

STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · DYNAMIC PROGRAMMING

    Min Cost Climbing Stairs in JavaScript, explained

    Understanding the Problem

    The core challenge of this problem is to find the minimum cost to reach the top of the staircase. The significance of this problem lies in its application to dynamic programming, where we need to make decisions at each step to minimize the overall cost. A common pitfall is to assume that starting from the first step is always optimal, which is not necessarily true.

    Approach

    To solve this problem, we can use dynamic programming. The idea is to keep track of the minimum cost to reach each step and use this information to calculate the minimum cost to reach the next steps.

    Naive Solution

    A naive solution would involve recursively calculating the cost for each possible path to the top. However, this approach is not optimal due to its exponential time complexity.

    Optimized Solution

    An optimized solution involves using dynamic programming to store the minimum cost to reach each step. This reduces the time complexity to O(n).

    Algorithm

    1. Initialize an array `minCost` where `minCost[i]` represents the minimum cost to reach step `i`.

    2. Set `minCost[0]` and `minCost[1]` to `cost[0]` and `cost[1]` respectively.

    3. For each step from 2 to n, calculate the minimum cost to reach that step using the formula:

    minCost[i] = cost[i] + Math.min(minCost[i-1], minCost[i-2])

    4. The result will be the minimum of the last two values in the `minCost` array, as you can reach the top from either of the last two steps.

    Code Implementation

    // Function to calculate the minimum cost to climb stairs
    function minCostClimbingStairs(cost) {
        // Initialize the first two steps
        let n = cost.length;
        let minCost = new Array(n);
        minCost[0] = cost[0];
        minCost[1] = cost[1];
    
        // Calculate the minimum cost for each step
        for (let i = 2; i < n; i++) {
            minCost[i] = cost[i] + Math.min(minCost[i - 1], minCost[i - 2]);
        }
    
        // The minimum cost to reach the top is the minimum of the last two steps
        return Math.min(minCost[n - 1], minCost[n - 2]);
    }
    
    // Example usage:
    console.log(minCostClimbingStairs([10, 15, 20])); // Output: 15
    console.log(minCostClimbingStairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])); // Output: 6
    

    Complexity Analysis

    The time complexity of this solution is O(n) because we iterate through the cost array once. The space complexity is also O(n) due to the additional array used to store the minimum costs.

    Edge Cases

    Potential edge cases include:

    • Cost array with only two elements.
    • Cost array with all elements being zero.
    • Cost array with maximum length and values.

    Each of these cases should be tested to ensure the algorithm handles them correctly.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases with small arrays.
    • Cases with varying costs.
    • Edge cases as mentioned above.

    Using a testing framework like Jest can help automate and manage these tests effectively.

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to:

    • Break down the problem into smaller sub-problems.
    • Consider both recursive and iterative solutions.
    • Optimize by storing intermediate results to avoid redundant calculations.

    Practicing similar dynamic programming problems can help improve problem-solving skills.

    Conclusion

    Understanding and solving the "Min Cost Climbing Stairs" problem helps in grasping dynamic programming concepts. It's crucial to practice and explore further to master such problems.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free