Min Cost Climbing Stairs — LeetCode 746 Python Solution

EasyArrayDynamic Programming
Problem
#746
Reading time
2 min

The problem

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

Example

Input
cost = [10,15,20]
Output
15
Explanation
You will start at index 1.

Python solution

Python
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        @cache
        def dfs(i: int) -> int:
            if i >= len(cost):
                return 0
            return cost[i] + min(dfs(i + 1), dfs(i + 2))

        return min(dfs(0), dfs(1))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array \textit{cost} auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 746. Min Cost Climbing Stairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and LeetCode 75.

Frequently asked questions

How hard is LeetCode 746. Min Cost Climbing Stairs?
LeetCode 746. Min Cost Climbing Stairs is rated Easy on LeetCode.
What is the time complexity of LeetCode 746. Min Cost Climbing Stairs?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 746. Min Cost Climbing Stairs?
The Python solution on this page uses O(n), where n is the length of the array \textit{cost} auxiliary space.
What topics does LeetCode 746. Min Cost Climbing Stairs cover?
LeetCode 746. Min Cost Climbing Stairs is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview