Yasir Explains/Algorithms/Dynamic Programming/Climbing Stairs
Dynamic Programming

Climbing Stairs

On this page

ProblemDP recurrence relationDP memoizationDP base casePseudocodeComplexity
Dynamic Programming

Climbing Stairs

Count ways to reach the n-th step using steps of size 1 or 2 — same recurrence shape as Fibonacci, written as explicit DP.

Problem

A staircase has n steps. From the ground you may move +1 or +2 steps at each move. Count how many distinct sequences of moves end exactly on step n.

DP recurrence relation

Let dp(n) = number of ways to reach step n (with dp(0) = 1 meaning one way to be at the start before the first move).

For n ≥ 1, your last move is either from step n − 1 (a 1-step) or from n − 2 (a 2-step), and those cases are disjoint:

Example
dp(n) = dp(n − 1) + dp(n − 2)

Explanation: Every path to step n must arrive from n−1 or n−2 exactly once; summing those two counts counts every path once.

DP memoization

Keep memo[0…n] with a sentinel (e.g. −1) for “unknown.” When dp(n) is needed, return memo[n] if it is already set; otherwise compute dp(n) using the recurrence on smaller indices, assign memo[n], then return.

Only n + 1 states exist, so the work is O(n).

DP base case

With dp(0) = 1 (one empty path at the ground):

Example
dp(1) = 1 // one 1-step from 0
dp(2) = dp(1) + dp(0) = 2

For n ≥ 3, only the recurrence applies. Alternatively, you can define dp(1) = 1, dp(2) = 2 directly and use the recurrence for n ≥ 3 — match your indexing to your implementation.

Pseudocode

Top-down with memo:

1CLIMB(n, memo)
2 if n <= 1
3 return 1 // dp(0) and dp(1) under convention above
4 if memo[n] != UNKNOWN
5 return memo[n]
6 memo[n] = CLIMB(n - 1, memo) + CLIMB(n - 2, memo)
7 return memo[n]

Complexity

Time: O(n). Space: O(n) for memo and recursion depth.

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Growth Rate Comparison

n (input size)O(1)O(log n)O(n)O(n log n)O(n²)