← DSA
EASY

Min Cost Climbing Stairs

PracticeNeetCode ↗LeetCode ↗

Given an array cost where cost[i] is the price of stepping on stair i, you may start from step 0 or step 1, and from any step you can climb 1 or 2 steps. Return the minimum total cost to reach the top — one step past the last stair.

Example

Input cost = [10,15,20]
Output 15

Key Pointers

Step-by-Step Analysis

  1. Initialize two running values: two_back = cost[0], one_back = cost[1].
  2. For each index i from 2 to the last index, compute current = cost[i] + min(one_back, two_back), then shift both values forward.
  3. After the loop, the answer is min(one_back, two_back) — the cheaper of the last two stairs, since the top is reachable from either.

Complexity

Time: O(n) — Space: O(1)

Code

def minCostClimbingStairs(cost: list[int]) -> int:
    two_back, one_back = cost[0], cost[1]
    for i in range(2, len(cost)):
        two_back, one_back = one_back, cost[i] + min(one_back, two_back)
    return min(one_back, two_back)

Code Explanation

How the solution above works, piece by piece.

  1. Let best(i) = the cheapest total cost of standing on step i (you pay cost[i] when you step on it). Steps 0 and 1 are free starting points, so best(0) = cost[0], best(1) = cost[1].
  2. Step i is reached from i − 1 or i − 2: best(i) = cost[i] + min(best(i−1), best(i−2)).
  3. Only the last two values are needed, so two variables replace a table; the tuple assignment shifts them each loop.
  4. The top is past the last step and can be reached from either of the last two steps, so return min(one_back, two_back).
  5. O(n) time, O(1) space.

Visual Walkthrough

Running it on cost = [10, 15, 20]:

trace100151202starttwo_back = 10, one_back = 15101520i=2step 2 total = 20 + min(15, 10) = 30101520endtop = min(30, 15) = 15: start on step 1, jump 2
Stepping on step 2 would cost 20 + 10 = 30. Jumping from step 1 (cost 15) straight past the end is cheaper, so the answer is 15.
one step backcurrent step

Video Explanation

NeetCode — Dynamic Programming, LeetCode 746