AlgoViz

Min Cost Climbing Stairs

easy 16 min

Each step has a toll; you may start on step 0 or 1, pay for every step you stand on, and climb one or two at a time.

See it run

Pay the toll on every step you stand on, climb one or two at a time, and find the cheapest way past the last step to the top.

Operations

Where the top is: [10, 15, 20]

Set up the problem on the smallest example. The top is not the last step: it sits one place past the end, at index n, and costs nothing. Then compare the two ways to define the state.

Step 1 of 6

Three steps and a top

steps 0..2, then the top at index n = 3

  1. 100
  2. 151
  3. 202
  4. top3goal
n = 3

cost = [10, 15, 20]. Standing on step i costs cost[i]. The top is index 3, one place past the last step, and it is free. You are done when you get there, not when you stand on step 2.

Step 1: Three steps and a top

def stand_on(cost):                     # dp[i] = cheapest total having paid for step i    n = len(cost)    dp = [cost[0], cost[1]] + [0] * (n - 2)    for i in range(2, n):        dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])    return min(dp[n - 1], dp[n - 2])    # top = index n: one or two hops awaydef reach(cost):                        # r[i] = cheapest total to arrive at i, toll not yet paid    n = len(cost)    r = [0] * (n + 1)                   # r[0] = r[1] = 0 and r[n] is the top    for i in range(2, n + 1):        r[i] = min(r[i - 1] + cost[i - 1], r[i - 2] + cost[i - 2])    return r[n]
Time
O(n)
Space
O(n)
answer
15
greedy (cheaper next step)
25, wrong

Say out loud what dp[i] means before writing any code. "Paid for step i" needs min of the last two at the end; "arrived at i" puts the answer in r[n]. Mixing them is the usual bug.

In the real world

The same min cost climbing stairs doing real jobs. Pick one and step through it.

The old "skip expensive" sample: cost = [1, 100, 1, 1, 100, 1]. Two 100-toll steps sit in the way, and the best route jumps over both.

Step 1 of 3

Two traps

cost[i]: toll to stand on step i

  1. 10
  2. 1001
  3. 12
  4. 13
  5. 1004
  6. 15

dp[i]: cheapest total having paid for step i

  1. ·0
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5

Steps 1 and 4 cost 100; everything else costs 1. The top is index 6.

Step 1: Two traps

cost = [1, 100, 1, 1, 100, 1]print(min_cost(cost))        # 4: stand on 0, 2, 3, 5

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Returning dp[n - 1]

    critical

    The top is index n, one past the last step, and it can be reached by a 2-step hop from n - 2. Returning dp[n - 1] forces you to stand on the last step. For [10, 15, 20] that gives 30 instead of 15.

    Wrong
    return dp[n - 1]                      # forces a stop on the last step
    Right
    return min(dp[n - 1], dp[n - 2])      # top reachable from either
  • dp[1] = cost[0] + cost[1]

    critical

    You may start on step 1 directly. Adding cost[0] makes every path pay for step 0 even when it should be skipped. For [5, 1, 5, 1, 5] the answer jumps from 2 to 7.

    Wrong
    dp[0] = cost[0]dp[1] = cost[0] + cost[1]             # as if you must start on step 0
    Right
    dp[0] = cost[0]dp[1] = cost[1]                       # starting on step 1 is free
  • Mixing the two definitions

    major

    "Paid for step i" adds costi and ends with a min of the last two. "Arrived at i" adds the toll of the step you leave and ends at r[n]. Taking the array size of one and the formula of the other indexes cost[n], which does not exist.

    Wrong
    r = [0] * (n + 1)for i in range(2, n + 1):    r[i] = cost[i] + min(r[i - 1], r[i - 2])   # IndexError at i = n
    Right
    r = [0] * (n + 1)for i in range(2, n + 1):    r[i] = min(r[i - 1] + cost[i - 1], r[i - 2] + cost[i - 2])return r[n]
  • Greedy: take the cheaper next step

    major

    Choosing the cheaper of the next two steps looks sensible but ignores what comes after. [10, 15, 20] gives 25 greedily against 15, and the ten-step classic gives 7 against 6.

    Wrong
    pos = 0 if cost[0] <= cost[1] else 1total = cost[pos]while pos < n - 2:    pos = pos + 1 if cost[pos + 1] <= cost[pos + 2] else pos + 2    total += cost[pos]
    Right
    for i in range(2, n):    dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])   # consider both, keep the bestreturn min(dp[n - 1], dp[n - 2])
  • Plain recursion for a long staircase

    major

    Without a memo the calls grow like 1.618ⁿ: about 2.7 million for 30 steps, far too many for 1,000. Add a cache or loop bottom-up.

    Wrong
    def f(i):    if i <= 1:        return cost[i]    return cost[i] + min(f(i - 1), f(i - 2))   # recomputes everything
    Right
    from functools import cache@cachedef f(i):    if i <= 1:        return cost[i]    return cost[i] + min(f(i - 1), f(i - 2))
  • Sliding the pair in the wrong order

    minor

    Two separate assignments overwrite prev1 before prev2 reads it, so both end up holding cur. Use one tuple assignment.

    Wrong
    prev1 = curprev2 = prev1          # copies cur, the old prev1 is lost
    Right
    prev2, prev1 = prev1, cur

Interview tips

  • How to explain it

    • dp[i] is the cheapest total having paid for step i: dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]).
    • Base cases dp[0] = cost[0] and dp[1] = cost[1], because you may start on either.
    • The top is index n, so the answer is min(dp[n - 1], dp[n - 2]). O(n) time, O(1) space with two variables.
  • Spot it in problems

    • Minimise a total cost (or maximise a total value) along a line of positions.
    • Each move goes forward a small fixed number of places: 1 or 2, or up to k.
    • Each position has its own cost or value: House Robber, Delete and Earn, Paint House, Jump Game II.
  • Memory tricks

    • COST: Current step's toll, Optimal of the previous two, Sum them, Track to the top.
    • Climbing stairs adds (count ways); min cost takes the min (cheapest way).
    • Toll road: you pay at every booth you stop at, and you may drive past one booth at a time.
  • Watch out

    • The top is past the last step: min of the last two, never just dp[n - 1].
    • dp[1] is cost[1], not cost[0] + cost[1].
    • Greedy fails: [10, 15, 20] proves it.
    • Keep the full table if the question asks for the path, not just the total.