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.

Video lesson · Chapter 1 of 6

The exit has no price tag

0:00 / 5:20

Min cost climbing stairs in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Define the state. dp[i] = the cheapest total having paid for step i; you may start on step 0 or step 1

Understand it

Start here

A staircase with a toll on every step

You get a list cost where cost[i] is the toll for standing on step ii. After paying, you climb 1 or 2 steps. You may begin on step 0 or step 1, and you want to reach the top for the smallest total toll. Our first example is cost = [10, 15, 20].

index0123
what it isstepstepsteptop
toll101520free
The top is index n=3n = 3, one place past the last step. Best here: start on step 1, pay 15, hop 2 to the top.

It is Climbing stairs with prices: the same 1-or-2 moves, but instead of counting ways we look for the cheapest one. If dynamic programming is new, start with Dynamic programming basics.

The rules

Four rules that shape the answer

  • Start on 0 or 1

    Nothing below your starting step is paid. So the cheapest way onto step 1 is just cost[1].

  • Pay where you stand

    Every step you land on charges its toll. Steps you hop over cost nothing.

  • Move 1 or 2

    From step ii you go to i+1i + 1 or i+2i + 2, so step ii is entered from i−1i - 1 or i−2i - 2.

  • The top is free

    Index nn has no toll. Reaching it ends the climb.

The moves around step i

Two ways in, two ways out. Looking backwards (ways in) gives the recurrence.

Optimisation: min cost

  • Input: a list of tolls cost.
  • Combine the two options with min.
  • dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]).

Counting: climbing stairs

  • Input: just the number of steps n.
  • Combine the two options with +.
  • ways[i] = ways[i - 1] + ways[i - 2].

The state

Two ways to define dp

There are two common definitions. Both are correct, and both give the same answer. Pick one and stick to it; this topic, its visualizer and its code all use the first.

Paid for step i (used here)

dp[i]=cost[i]+min⁡(dp[i−1], dp[i−2]),dp[0]=cost[0],  dp[1]=cost[1],answer=min⁡(dp[n−1], dp[n−2])\text{dp}[i] = \text{cost}[i] + \min(\text{dp}[i-1],\, \text{dp}[i-2]), \quad \text{dp}[0] = \text{cost}[0],\; \text{dp}[1] = \text{cost}[1], \quad \text{answer} = \min(\text{dp}[n-1],\, \text{dp}[n-2])
The toll of step ii is already inside dp[i]\text{dp}[i]. The top is not a cell, so the answer takes the cheaper of the last two cells.

Arrived at step i, toll not yet paid

r[i]=min⁡(r[i−1]+cost[i−1],  r[i−2]+cost[i−2]),r[0]=r[1]=0,answer=r[n]r[i] = \min(r[i-1] + \text{cost}[i-1],\; r[i-2] + \text{cost}[i-2]), \quad r[0] = r[1] = 0, \quad \text{answer} = r[n]
You pay the toll of the step you leave. The array has n+1n + 1 cells and the top is the last one. For [10, 15, 20]: r=[0,0,10,15]r = [0, 0, 10, 15].

The recurrence

Pay here, plus the cheaper way in

The full recurrence

dp[i]={cost[0]i=0cost[1]i=1cost[i]+min⁡(dp[i−1],dp[i−2])2≤i≤n−1\text{dp}[i] = \begin{cases} \text{cost}[0] & i = 0 \\ \text{cost}[1] & i = 1 \\ \text{cost}[i] + \min(\text{dp}[i-1], \text{dp}[i-2]) & 2 \le i \le n-1 \end{cases}
Optimal substructure: the cheapest path onto step ii must use the cheapest path onto whichever step it came from.

Filling one cell

Every cell is one comparison and one addition: O(1)O(1) work.

For [10, 15, 20]: dp[0] = 10, dp[1] = 15, dp[2] = 20 + min(15, 10) = 30. The answer is min⁡(30,15)=15\min(30, 15) = 15. Notice that greedy, which starts on the cheaper step 0 and then picks the cheaper next step, pays 10+15=2510 + 15 = 25.

Brute force

Plain recursion and its repeated work

Python
def min_cost_brute(cost):    def f(i):                       # cheapest total having paid for step i        if i <= 1:            return cost[i]          # start on step 0 or step 1        return cost[i] + min(f(i - 1), f(i - 2))    n = len(cost)    return min(f(n - 1), f(n - 2))  # the top is one or two hops awayprint(min_cost_brute([10, 15, 20]))         # 15print(min_cost_brute([1, 100, 1, 1, 100]))  # 3
The recurrence typed straight in. Correct, but it recomputes the same steps again and again.
Edit and run it in your browser

Calls for cost = [1, 100, 1, 1, 100]

14 calls of f for 5 distinct steps. The red calls repeat work already done: overlapping subproblems.

How many calls?

C(i)=C(i−1)+C(i−2)+1,  C(0)=C(1)=1  ⟹  C(n−1)+C(n−2)=2F(n+1)−2=Θ(φn)C(i) = C(i-1) + C(i-2) + 1,\; C(0) = C(1) = 1 \;\Longrightarrow\; C(n-1) + C(n-2) = 2F(n+1) - 2 = \Theta(\varphi^n)
The same shape as Fibonacci, so the calls grow by about φ≈1.618\varphi \approx 1.618 per extra step: 14 for n=5n = 5, 21,890 for n=20n = 20, about 2.7 million for n=30n = 30. Usually quoted as O(2n)O(2^n); the stack is O(n)O(n) deep.

Fix 1

Memoisation: each step once

Only nn different questions exist, f(0) to f(n - 1). Store each answer the first time it is computed and look it up after that. The repeated subtrees above each become one lookup: 14 calls drop to 8, and in general to 2n−22n - 2.

A memoised call

Each ii reaches the bottom box once, so the time is O(n)O(n). Space is O(n)O(n) for the memo plus O(n)O(n) for the stack.
Python
from functools import cachedef min_cost_memo(cost):    @cache    def f(i):        if i <= 1:            return cost[i]        return cost[i] + min(f(i - 1), f(i - 2))    n = len(cost)    return min(f(n - 1), f(n - 2))print(min_cost_memo([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))  # 6
@cache does the lookup and the store. Defining f inside keeps the cache fresh for each input.
Edit and run it in your browser

Fix 2

Tabulation: fill dp left to right

i0123456789
cost[i]1100111100111001
dp[i]1100233103451046
The classic ten-step input. The answer is min⁡(dp[9],dp[8])=min⁡(6,104)=6\min(\text{dp}[9], \text{dp}[8]) = \min(6, 104) = 6: six tolls of 1, every 100 skipped.
From tolls to answer
  1. 1Cost array[1, 100, 1, ...]
  2. 2Base casesdp[0], dp[1]
  3. 3Build dpcost[i] + min of two
  4. 4Find minmin(dp[n-1], dp[n-2])
  5. 5Result6
Python
def min_cost_table(cost):    n = len(cost)    if n < 2:        return 0                    # one step: start on step 1, which is the top    dp = [0] * n    dp[0], dp[1] = cost[0], cost[1]    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])print(min_cost_table([10, 15, 20]))                        # 15print(min_cost_table([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))  # 6
Bottom-up in O(n)O(n) time and O(n)O(n) space. No recursion, so no recursion limit.
Edit and run it in your browser

Fix 3

O(1) space with a rolling pair

The loop reads only dp[i - 1] and dp[i - 2]. Keep them in two variables, prev1 and prev2, and slide the pair one step after each cell. Time stays O(n)O(n); space drops to O(1)O(1).

Python
def min_cost(cost):    prev2, prev1 = cost[0], cost[1]       # dp[i - 2], dp[i - 1]    for i in range(2, len(cost)):        cur = cost[i] + min(prev1, prev2)        prev2, prev1 = prev1, cur         # slide the pair    return min(prev1, prev2)print(min_cost([1, 2, 3, 4, 5]))   # 6print(min_cost([5, 1, 5, 1, 5]))   # 2
The interview answer. One tuple assignment slides both values safely.
Edit and run it in your browser

Which steps?

Reconstructing the cheapest path

The table knows more than the total. Start at the top, step back to whichever of the last two cells is cheaper, and keep stepping back to the cheaper predecessor until you reach step 0 or 1. Reverse the list.

Walking the table backwards

For the ten-step input the walk visits 9, 7, 6, 4, 2, 0, so the path is 0 → 2 → 4 → 6 → 7 → 9 → top, total 6.
Python
def cheapest_path(cost):    n = len(cost)    dp = cost[:2] + [0] * (n - 2)    for i in range(2, n):        dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])    i = n - 1 if dp[n - 1] <= dp[n - 2] else n - 2    path = [i]    while i > 1:        i = i - 1 if dp[i - 1] <= dp[i - 2] else i - 2        path.append(i)    return path[::-1]cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]p = cheapest_path(cost)print(p, sum(cost[i] for i in p))   # [0, 2, 4, 6, 7, 9] 6
Needs the full table: the rolling pair forgets the cells it would walk back through.
Edit and run it in your browser

Comparison

Every approach side by side

ApproachTimeSpaceNotes
Greedy (cheaper next step)O(n)O(n)O(1)O(1)Wrong: [10, 15, 20] gives 25, not 15
Plain recursionΘ(φn)\Theta(\varphi^n), so O(2n)O(2^n)O(n)O(n) stackFixes the meaning of f(i); too slow past about 30 steps
Memoised recursionO(n)O(n)O(n)O(n) memo + stackQuick to write; recursion limit for long inputs
Table (bottom-up)O(n)O(n)O(n)O(n)Keeps every value, so the path can be rebuilt
Rolling pairO(n)O(n)O(1)O(1)The usual final answer
Every DP version touches each step once. The only difference is how much it remembers.
AspectClimbing stairsMin cost climbing
GoalCount the waysMinimise the total cost
OperationAddition (+)Minimum (min)
Recurrenceways[i-1] + ways[i-2]cost[i] + min(dp[i-1], dp[i-2])
Inputn, the number of stepscost[], a toll per step
TypeCounting problemOptimisation problem
Same moves, different question. Swap + for min and add a toll, and one becomes the other.

Pattern spotting

Where this shape shows up again

Is it this pattern?

Min cost climbing is a shortest path on a line where each step links to the next two. See Dynamic programming basics for the general recipe.
  • House robber

    Take house ii plus the best up to i−2i - 2, or skip it: max⁡\max instead of min⁡\min. See House robber.

  • Jump game II

    Fewest jumps to the end when each cell says how far you may jump: the same "best way in" idea over a wider window.

  • Delete and earn, paint house

    Pick values along a line with a rule about neighbours. One row of DP, a min or a max, the last two or three cells.

Recap

Key takeaways

Key points

  • You pay the toll of every step you stand on, start on step 0 or 1, and climb 1 or 2.
  • The top is index n, past the last step, so the answer is min(dp[n - 1], dp[n - 2]).
  • dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]) with dp[0] = cost[0] and dp[1] = cost[1].
  • The other definition, r[i] = cost to arrive at i, ends at r[n]. Pick one and do not mix them.
  • Plain recursion is Θ(φⁿ); memoisation and tabulation are O(n); a rolling pair is O(1) space.
  • Greedy fails: [10, 15, 20] costs 25 greedily but 15 at best.
  • Keep the table and walk back to the cheaper predecessor to recover the path.

Sources