easy

Min Cost Climbing Stairs

Find the cheapest way to reach the top of a staircase where every step has a cost.

1. Define the problem

Min Cost Climbing Stairs

You are given an array cost where costi is the cost of stepping on stair i. Once you pay the cost, you can climb 1 or 2 steps. You can start from step 0 or step 1, and the top is one step past the last index. Return the minimum cost to reach the top. The cheapest way to reach step i is costi plus the cheaper of the two smaller subproblems already solved for step i-1 and step i-2 — the same overlapping subproblems pattern as counting ways, but tracking a running minimum instead of a running sum.

Constraints

  • 2 ≤ cost.length ≤ 1000
  • 0 ≤ costi ≤ 999

Example

Inputcost = [10, 15, 20]
Output15

Explanation Start on step 1 (cost 15) and jump straight to the top, which is cheaper than any path through step 0.

2. Visualize the solution

Track the cheaper of the two previous steps

Track the cheaper of the two previous steps
Statusbase

The whole table for cost = [10, 15, 20] is laid out. dp[0] = 10 and dp[1] = 15 are the base cases; dp[2] is still blank.

What happens in this step

cost = [10, 15, 20]
dp[0] = cost[0] = 10
dp[1] = cost[1] = 15

You can start at either step 0 or step 1, so both are seeded directly from their own cost. dp[2] has not been worked out yet.
Step 1 of 3

Steps to visualize

  1. Set the base cases: dp0 = cost0 and dp1 = cost1.
  2. For every step i from 2 onward, dpi = costi + min(dp[i-1], dp[i-2]).
  3. The answer is the cheaper of the final two steps, since the top can be reached from either.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Track the cheaper of the two previous steps
Statusbase

The whole table for cost = [10, 15, 20] is laid out. dp[0] = 10 and dp[1] = 15 are the base cases; dp[2] is still blank.

What happens in this step

cost = [10, 15, 20]
dp[0] = cost[0] = 10
dp[1] = cost[1] = 15

You can start at either step 0 or step 1, so both are seeded directly from their own cost. dp[2] has not been worked out yet.
Step 1 of 3
4. Solution

Solution

solution.tsTypeScript
function minCostClimbingStairs(cost) {
  const n = cost.length;
  let prev2 = cost[0];
  let prev1 = cost[1];

  for (let i = 2; i < n; i++) {
    const curr = cost[i] + Math.min(prev1, prev2);
    prev2 = prev1;
    prev1 = curr;
  }

  return Math.min(prev1, prev2);
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
cost = [10, 15, 20]15example from the docstring
cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]6longer array where skipping expensive steps pays off
cost = [1, 2]1smallest valid array, just two steps
cost = [5, 5, 5, 5]10every step costs the same
cost = [1, 2, 3, 4]4strictly increasing costs
cost = [0, 0, 0, 0, 0]0every step is free
cost = [3, 1, 2, 4, 1]4mixed costs with no obvious pattern