Climbing Stairs — LeetCode 70 Python Solution

EasyMemoizationMathDynamic Programming
Problem
#70
Reading time
2 min

The problem

You are climbing a staircase. It takes n steps to reach the top.

Example

Input
n = 2
Output
2
Explanation
There are two ways to climb to the top.

Python solution

Python
class Solution:
    def climbStairs(self, n: int) -> int:
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return b

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 70. 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 and Memoization.

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 Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 70. Climbing Stairs?
LeetCode 70. Climbing Stairs is rated Easy on LeetCode.
What is the time complexity of LeetCode 70. Climbing Stairs?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 70. Climbing Stairs?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 70. Climbing Stairs cover?
LeetCode 70. Climbing Stairs is tagged Memoization, Math 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