EasyNo. 0070

Climbing Stairs — LeetCode 70 Python Solution

Topics
Memoization, Math, Dynamic Programming
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

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

Complexity

Time
O(n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0241Different Ways to Add ParenthesesMedium
0464Can I WinMedium
0509Fibonacci NumberEasy
0913Cat and MouseHard
0964Least Operators to Express NumberHard
1137N-th Tribonacci NumberEasy

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.

Free to download. Check it runs on your machine, then pick a plan.