Climbing Stairs

Count the ways to climb a staircase when each move goes up one stair or two.

A staircase has n steps, and you start at the bottom. Each move climbs either 1 or 2 steps. Return the number of distinct ways to reach the top, where two ways are different if their sequences of moves differ.

Example 1
Input: n = 2
Output: 2
Explanation: 1 + 1, or 2.
Example 2
Input: n = 3
Output: 3
Explanation: 1 + 1 + 1, 1 + 2, or 2 + 1.
Solution

The Idea

Going up a staircase, you can take the stairs one at a time or skip one now and then. Example 2 has three steps, and there are three ways up: 1 + 1 + 1, 1 + 2 and 2 + 1. Each number is one move, and each move climbs one stair or two.

Writing every way down works for three steps, but the lists grow quickly: a staircase of 10 steps already has 89 ways up. Can we count the ways without listing them?

Look at the last move instead of the whole climb. Every way to reach step 3 ends with a move onto step 3, and that move is either one stair, from step 2, or two stairs, from step 1. In Example 2, 1 + 1 + 1 and 2 + 1 end with one stair. Before that stair they are 1 + 1 and 2, the two ways to reach step 2. The way 1 + 2 ends with two stairs, and before them is 1, the one way to reach step 1.

Look at the picture below. Step 0 is the floor, where you stand at the start, and the number above each step is how many ways reach that step from step 0.

A staircase from step 0 to step 5 with the ways to reach each step: 1, 1, 2, 3, 5 and 8. Step 3 gets its 3 from the 2 ways to reach step 2, one stair below, plus the 1 way to reach step 1, two stairs below.

The orange step 3 gets its 3 by adding the 2 above step 2, along the arrow labelled one stair, and the 1 above step 1, along the arrow labelled two stairs. No way is counted twice, because a way that ends with one stair can never also end with two.

The same holds for every step: the ways to reach a step are the ways to reach the step just below it plus the ways to reach the step two below. Starting at the floor, each count comes from two counts already known, which gives 1, 1, 2, 3, 5 and 8 for steps 0 to 5. Each of these numbers is the sum of the two before it, so they are the Fibonacci numbers, which Dynamic Programming Basics also builds on.

Solution Approach

Turning the last-move idea into code means settling three things: why counting with a method that calls itself is slow, which counts the climb starts from, and how many counts to keep.

Counting with a method that calls itself

Why not write the rule as a method ways(n) that returns ways(n - 1) + ways(n - 2)? It gives the right answer, but each call makes two more calls, and many of them ask the same question. ways(5) asks for ways(4) and ways(3), and ways(4) then asks for ways(3) again. In a test run, ways(5) made 15 calls and ways(40) made 331,160,281.

One fix is to save each step's count the first time ways works it out, and hand it back when ways(3) or any other step is asked for again. Saving answers this way is called memoization, and then each step is worked out once. Filling the counts from step 0 upward reaches the same result without the extra calls. Building the answer for a tall staircase from the answers for shorter ones, kept as you go, is called dynamic programming.

The starting counts

Where does the climb start? The rule needs two counts below a step, so steps 0 and 1 get theirs directly. There is one way to be on step 0: make no move. There is one way to reach step 1: a single stair. From these, step 2 gets 1 + 1 = 2, which matches Example 1.

Keeping only two counts

Does every count have to be kept? The count for a step uses only the two counts right below it. Once step 4 is known, the count for step 2 is never read again. So two variables are enough, one for the step just below and one for the step two below, and they move up the staircase one step at a time.

Java Solution

The method climbStairs works in these steps:

  1. First, set twoBelow and oneBelow to 1, the counts for step 0 and step 1.
  2. Then a loop moves step from 2 up to n. Inside, ways becomes oneBelow + twoBelow, the count for step.
  3. Still inside the loop, both variables move up one step: twoBelow takes the value of oneBelow, and only then does oneBelow take ways, so the count for the step below is copied before it is replaced.
  4. When the loop ends, oneBelow holds the count for step n, and the method returns it. For n of 0 or 1 the loop does not run, and the method returns 1.

The main method runs both examples, a single step, every staircase from 0 to 10 steps, and a staircase of 45 steps.

Java
import java.util.ArrayList;
import java.util.List;

public class ClimbingStairs {

    public static int climbStairs(int n) {
        int twoBelow = 1; // ways to reach step 0
        int oneBelow = 1; // ways to reach step 1
        for (int step = 2; step <= n; step++) {
            int ways = oneBelow + twoBelow; // last move was 1 stair or 2 stairs
            twoBelow = oneBelow;
            oneBelow = ways;
        }
        return oneBelow;
    }

    public static void main(String[] args) {
        System.out.println(climbStairs(2));
        System.out.println(climbStairs(3));
        System.out.println(climbStairs(1));
        List<Integer> counts = new ArrayList<>();
        for (int n = 0; n <= 10; n++) {
            counts.add(climbStairs(n));
        }
        System.out.println("steps 0 to 10: " + counts);
        System.out.println(climbStairs(45));
    }
}

Running it prints:

Output
2
3
1
steps 0 to 10: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1836311903

The answers 2 and 3 match Examples 1 and 2, and the 1 for a single step is one stair. The line starting with steps 0 to 10 begins with 1, 1, 2, 3, 5 and 8, the numbers above the steps in the picture. Each later count is the sum of the two before it, up to 89 for 10 steps.

The last line says a staircase of 45 steps has 1,836,311,903 ways up, which is close to the largest value a Java int can hold, 2,147,483,647. For 46 steps the true count is 2,971,215,073, too big for an int, and in a test run the same method returned -1323752223. For taller staircases, make the three counts and the return type long.

The original implementation, ClimbingStairs.java, is on GitHub.

Complexity

The method does a fixed amount of work for each step and keeps no list of counts.

  • Time: O(n), because the loop visits each step from 2 to n once, and each visit is one addition and two copies.
  • Space: O(1), because only oneBelow, twoBelow and ways are kept, however tall the staircase is.

When each step has a cost and you want the cheapest climb, see Min Cost Climbing Stairs.