Climbing stairs
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Climbing stairs asks how many different ways you can reach step n if you may climb 1 or 2 steps at a time. The ways to reach step n equal the ways to reach the previous step plus the ways to reach the step before that. It is the friendly starting point for every "count the ways" problem.
Practical use cases
- Web app: Ways to pay in instalments. A finance page lets customers pay a bill using instalments of either one or two months. The page shows how many different payment plans exist for a 12-month bill. Counting ways for each month from the previous two gives 233 plans in a short loop. The customer sees a clear plan count, and the support team can quickly explain the choices without opening a calculator.
- Web app: Game level and combo counts. A game backend counts how many ways a player can reach a score using 1-point and 2-point moves, to design reward tiers. Building the counts up level by level avoids trying every sequence of moves, which would be millions. The designers can adjust the point values or add a 3-point move, and the same loop with one more term gives a new count in a second.
- System: Route counting and packing. Route counters on maps and packing programs count the ways to fill a space with pieces of two sizes. They use this same add-the-last-two rule. Anywhere you must count combinations of small steps, from tiling floors to counting button sequences, the add-the-previous-answers rule from the staircase appears again.
The story: The Stairs of the Old Fort
Kabir visited a hill fort with a long stone staircase. A guide said: "You may climb 1 or 2 steps at a time. In how many different ways can you reach the top?" Kabir started listing: 1+1+1, 1+2, 2+1... and quickly got tangled.
Mira whispered a clever thought: "Forget the whole staircase. Think about just the last move." To land on step 5, the very last jump came either from step 4 (a 1-step hop) or from step 3 (a 2-step hop). So ways to reach step 5 = ways to reach step 4 + ways to reach step 3.
The same thought works for step 4, step 3, every step. Better still, whenever they worked out a step, they wrote the answer on the wall so they never had to work it out twice. That habit, remember the small answers so you never redo them, is the heart of Dynamic Programming.
How to spot this problem, and where you need it
You need to know how many different ways exist to reach a total using a few kinds of small steps, and listing every way would take forever.
Signs you need it
- The problem says "how many distinct ways" to reach n using steps of fixed sizes.
- The ways to reach n can be explained by the last step taken, which leads back to smaller n.
- Listing all the ways with loops works for 10 but takes forever for 50.
Where to use it in a project
- Counting payment plans, instalment schedules or bundle combinations in a billing feature.
- Counting possible routes or move sequences in games and puzzle apps.
The solution
Say ways(0) is 1 and ways(1) is 1. For each next step n, the last move was either a 1-step from n-1 or a 2-step from n-2, so ways(n) is ways(n-1) plus ways(n-2). Loop from 2 up to the target, keeping just the previous two values. If other step sizes are allowed, add one more term for each. You get the count without ever listing the ways.
Payoff: Before: listing every sequence, millions of items for 30 steps. After: 30 additions and the exact count.
Explain it like I am 8
Imagine you are building a tower of blocks, but each new floor is simply made by adding the last two floors' answers together. You write each floor's answer in a notebook. When you need an old answer, you do not recompute. You just read it.
How it works, step by step
- Define the question.
ways[i]= how many ways to reach stepi. - Start with obvious answers (base cases).
ways[0] = 1(stay put),ways[1] = 1. - Use the last-move idea.
ways[i] = ways[i - 1] + ways[i - 2]. - Fill the notebook from small to big (tabulation), or recurse and cache (memoization). Either way, each step is solved once.
The code in four languages
PHP
<?php
// Memoization: recurse, but remember answers
function ways(int $n, array &$memo = []): int {
if ($n <= 1) return 1; // base cases
if (isset($memo[$n])) return $memo[$n]; // already in the notebook
return $memo[$n] = ways($n - 1, $memo) + ways($n - 2, $memo);
}
// Tabulation with only two variables (space O(1))
function waysFast(int $n): int {
$prev = 1; $curr = 1;
for ($i = 2; $i <= $n; $i++) {
[$prev, $curr] = [$curr, $prev + $curr]; // slide the window
}
return $curr;
}
echo waysFast(5); // 8JavaScript
// Memoization: recurse, but remember answers
function ways(n, memo = {}) {
if (n <= 1) return 1; // base cases
if (memo[n] !== undefined) return memo[n]; // already in the notebook
return (memo[n] = ways(n - 1, memo) + ways(n - 2, memo));
}
// Tabulation with only two variables (space O(1))
function waysFast(n) {
let prev = 1, curr = 1;
for (let i = 2; i <= n; i++) {
[prev, curr] = [curr, prev + curr]; // slide the window
}
return curr;
}
console.log(waysFast(5)); // 8Java
import java.util.*;
public class Main {
// Memoization: recurse, but remember answers
static long ways(int n, Map<Integer, Long> memo) {
if (n <= 1) return 1; // base cases
if (memo.containsKey(n)) return memo.get(n); // already in the notebook
long result = ways(n - 1, memo) + ways(n - 2, memo);
memo.put(n, result);
return result;
}
// Tabulation with only two variables (space O(1))
static long waysFast(int n) {
long prev = 1, curr = 1;
for (int i = 2; i <= n; i++) {
long next = prev + curr; // slide the window
prev = curr;
curr = next;
}
return curr;
}
public static void main(String[] args) {
System.out.println(waysFast(5)); // 8
System.out.println(ways(5, new HashMap<>())); // 8
}
}Go
package main
import "fmt"
// Memoization: recurse, but remember answers
func ways(n int, memo map[int]int) int {
if n <= 1 {
return 1 // base cases
}
if v, ok := memo[n]; ok {
return v // already in the notebook
}
memo[n] = ways(n-1, memo) + ways(n-2, memo)
return memo[n]
}
// Tabulation with only two variables (space O(1))
func waysFast(n int) int {
prev, curr := 1, 1
for i := 2; i <= n; i++ {
prev, curr = curr, prev+curr // slide the window
}
return curr
}
func main() {
fmt.Println(waysFast(5)) // 8
fmt.Println(ways(5, map[int]int{})) // 8
}Time: O(n) · Extra space: O(n), or O(1) with two variables. Without remembering, the plain recursion repeats work and explodes to roughly O(2ⁿ).
Watch out for
- Skipping the cache. Plain recursion recomputes the same steps over and over and becomes painfully slow around n = 40.
- Wrong base cases. Check tiny inputs (n = 0, 1, 2) by hand first.
Quick check
- To reach step 5, the last move came from…
- Step 4 or step 3
- Step 1 only
- Step 6
- What is the main idea of dynamic programming?
- Remember small answers to avoid repeating work
- Always use recursion
- Sort first
- With the notebook (memo), time becomes…
- O(n)
- O(2ⁿ)
- O(n²)