InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Min Cost Climbing Stairs

easy Original ↗ 00:00

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

The bounds are small, so any linear solution runs well within limits. The difficulty 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug