Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

Climbing Stairs in Java: O(n) Dynamic Programming

Practice O(n) Read the full explanation

You get an integer n, the number of steps in a staircase. Each move takes you up 1 step or 2 steps.

Return how many different ways you can climb from the bottom to exactly the top.

The order of the moves matters. For example, 1 + 2 and 2 + 1 are two different ways.

Example 1:

Input: n = 4
Output: 5
Explanation: The five ways are:
1. 1 + 1 + 1 + 1
2. 1 + 1 + 2
3. 1 + 2 + 1
4. 2 + 1 + 1
5. 2 + 2

Example 2:

Input: n = 1
Output: 1
Explanation: One move of 1 step is the only way.

Example 3:

Input: n = 6
Output: 13
Explanation: Group the ways by how many 2s they use:
no 2s: 1 way (1 + 1 + 1 + 1 + 1 + 1),
one 2: 5 ways (2 + 1 + 1 + 1 + 1 in any order),
two 2s: 6 ways (2 + 2 + 1 + 1 in any order),
three 2s: 1 way (2 + 2 + 2).
In total, 1 + 5 + 6 + 1 = 13.

Constraints:

  • n is from 1 to 45.
  • The answer fits in a 32-bit signed integer.
  • For n = 45, the answer is 1,836,311,903.

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · DYNAMIC PROGRAMMING

    Climbing Stairs in Java, explained

    Problem overview

    The method climbStairs receives the number of steps n and returns how many distinct ways there are to climb them, taking 1 or 2 steps at a time. Order matters: 1 + 2 and 2 + 1 count as two different ways.

    For n = 4 the answer is 5: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. The constraints are 1 <= n <= 45, and the answer fits in an int.

    Approach: build up from the ground

    Listing every sequence of moves works for small n but the number of sequences grows quickly, so it is better to count instead of list. Look at the last move before standing on step i. It was either a 1-step move from step i - 1 or a 2-step move from step i - 2. Those two groups never overlap, so

    ways(i) = ways(i - 1) + ways(i - 2)

    This is dynamic programming: each answer reuses answers for smaller steps. The pattern is the Fibonacci sequence. Running it for n = 1, 2, 3, 4, 5, 10 gives 1, 2, 3, 5, 8, 89.

    A table with one entry per step would work, but ways(i) only needs the two entries just below it. Two int variables are enough, which keeps the extra space constant.

    Step by step

    1. Create prev = 1, the ways to stand on step 0. There is exactly one: don't move. Counting it makes step 2 come out as 1 + 1 = 2.
    2. Create curr = 1, the ways to reach step 1, a single 1-step move. When n is 1, the loop never runs and curr is already the answer.
    3. Loop i from 2 to n inclusive. Step n is the top, and it needs its count too, so the condition is i <= n. At the start of each round, curr holds the count for step i - 1 and prev the count for step i - 2.
    4. Add the two counts into ways, the count for step i.
    5. Slide the window up. Set prev = curr first, then curr = ways. Reversing the order overwrites the value prev needs.
    6. Return curr. After the last round it holds the count for step n.

    The solution in Java

    class Solution {
        public int climbStairs(int n) {
            int prev = 1;
            int curr = 1;
            for (int i = 2; i <= n; i++) {
                int ways = prev + curr;
                prev = curr;
                curr = ways;
            }
            return curr;
        }
    }
    

    Java details worth noticing:

    • Local variables only. prev, curr and ways are plain int locals. ways is declared inside the loop, so a fresh one exists in every round.
    • int overflow is silent. Java does not throw when an int goes past 2,147,483,647: it wraps around to a negative number. The constraint n <= 45 is what keeps this safe. For n = 45 the method returns 1836311903, but for n = 46 it returns -1323752223, and for n = 50 it returns -1109825406. Nothing warns you, so a long would be needed for bigger inputs, and eventually even that overflows.
    • Assignment order. The two assignments inside the loop run top to bottom. The sequence prev = curr; curr = ways; is correct because ways was computed before either variable changed.

    Complexity

    Time: O(n). The loop runs n - 1 times and each round does a constant amount of work.

    Space: O(1). Only three integers are used, whatever the value of n. A full table of n + 1 entries would cost O(n), and a plain recursive version with no memory of earlier answers would take exponential time, since it recomputes the same steps many times.

    Edge cases and common mistakes

    • n = 1. The loop starts at 2 and never runs, and the method returns the initial curr, 1.
    • n = 2. One round runs: ways = 1 + 1 = 2, and the method returns 2.
    • Writing i < n. The loop then stops one round early and returns the count for step n - 1. For n = 4 that gives 3 instead of 5.
    • Starting prev at 0. The count for the ground is 1, not 0. With 0, step 2 would count 0 + 1 = 1 way instead of 2.
    • Overwriting in the wrong order. curr = ways; prev = curr; leaves both variables equal, so the sum doubles one count instead of adding two.

    Testing

    • n = 1 gives 1.
    • n = 2 gives 2.
    • n = 3 gives 3.
    • n = 4 gives 5.
    • n = 5 gives 8.
    • n = 45 gives 1836311903.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free