InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Min Cost Climbing Stairs

easy Original β†—
Solving tips
  • Define state as cost to ARRIVE at position i: reach(i) = min(reach(i-1)+cost[i-1], reach(i-2)+cost[i-2]).
  • Choosing 'arrive at' over 'leave' makes both free starts collapse to reach(0)=reach(1)=0, keeping base cases clean.
  • The goal is index n (one past the last stair), not n-1, so the answer is reach(n) - returning dp[n-1] undercounts.
  • Collapse to two rolling variables for O(n) time, O(1) space.

Problem

You are given an array cost where cost[i] is the price of stepping off stair i. From any stair you may move 1 or 2 stairs upward. You may begin from stair 0 or stair 1 for free (you only pay when you leave a stair).

The β€œtop” is the position just beyond the last stair (index len(cost)). Return the minimum total cost to reach the top.

Examples

  • cost = [10, 15, 20] β†’ 15 β€” start on stair 1, pay 15, take a double step past stair 2 to the top.
  • cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] β†’ 6 β€” start on stair 0, then repeatedly hop over the 100s, paying 1 six times.
  • cost = [0, 0, 0, 1] β†’ 0 β€” every stair through index 2 is free, and a double step from stair 2 to the top skips the 1 on stair 3 entirely; total 0.

Constraints

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999

Small bounds, so any linear approach is instant; the challenge is defining the state and base cases cleanly.

Think about it first

Hint 1 Think about the cost to *arrive at* each position (not to leave it). Arriving at the top is what you want to minimize. From where could your final move to the top have come?
Hint 2 To arrive at position `i`, your last move was a single step from `i-1` (costing `cost[i-1]` to leave it) or a double step from `i-2` (costing `cost[i-2]`). So `reach(i) = min(reach(i-1) + cost[i-1], reach(i-2) + cost[i-2])`.
Hint 3 Base cases: `reach(0) = reach(1) = 0` because you start on either for free. Compute upward to `reach(len(cost))`. Only the last two values matter, so two rolling variables give O(1) space.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.