Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

Climbing Stairs in Rust: Dynamic Programming with Two Variables

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

    RUST · DYNAMIC PROGRAMMING

    Climbing Stairs in Rust, explained

    Problem overview

    The function climb_stairs receives n, the number of steps in a staircase, and returns in how many distinct ways you can climb to the top when each move is 1 or 2 steps. Order matters: 1 step then 2 steps is a different way from 2 steps then 1.

    For n = 3 the answer is 3: 1+1+1, 1+2 and 2+1. For n = 4 it is 5. The constraints keep n between 1 and 45, and the answer always fits in an i32.

    Approach: build the counts from the ground up

    Think about the very last move. To stand on step k, you either came from step k - 1 with a 1-step move, or from step k - 2 with a 2-step move. These two groups of ways never overlap, because the last move differs. So:

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

    This is dynamic programming: each answer is built from smaller answers that are already known. Computing ways(k) by plain recursion would repeat the same sub-problems many times and take exponential time. Going from the bottom up computes each step once.

    The recurrence only looks two steps back, so there is no need for a whole table. Two variables are enough: the count for the step just below the current one, and the count for the step below that.

    Step by step

    1. Create prev with let mut, set to 1. It stands for step 0, the ground. There is exactly one way to be there: don't move. Counting it is what makes step 2 come out as 1 + 1 = 2.
    2. Create curr, also 1. Step 1 can only be reached with a single 1-step move. When n is 1, this is already the answer.
    3. Loop over the steps 2 to n with for _ in 2..=n. The range ..= includes its end, so step n is counted. The loop doesn't need the step number, so the variable is named _. For n = 1 the range 2..=1 is empty and the body never runs.
    4. Add the two counts into a new variable ways. That is the number of ways to reach the step this round is counting.
    5. Shift the window up one step: prev takes the value of curr, then curr takes ways. The order matters. If curr were overwritten first, prev would receive the new value and the old one would be lost.
    6. Return curr, with no semicolon, as the last expression. After the last round it holds the count for step n.

    The solution in Rust

    impl Solution {
        fn climb_stairs(n: i32) -> i32 {
            let mut prev = 1;
            let mut curr = 1;
            for _ in 2..=n {
                let ways = prev + curr;
                prev = curr;
                curr = ways;
            }
            curr
        }
    }
    

    For n = 5, the values after each round are:

    step 2: prev=1 curr=2
    step 3: prev=2 curr=3
    step 4: prev=3 curr=5
    step 5: prev=5 curr=8

    so climb_stairs(5) returns 8. The counts 1, 1, 2, 3, 5, 8 are the Fibonacci numbers.

    The Rust details worth a closer look:

    • Inferred types. prev and curr are never annotated. The final curr is returned as an i32, so the compiler gives both variables that type.
    • mut is required. Variables are immutable by default. prev, curr and nothing else change, which is why ways is a plain let.
    • ..= against ... 2..n stops before n and would leave out the last step.
    • The _ loop variable. It tells Rust, and the reader, that the counter is deliberately unused. A named but unused variable would trigger a warning.
    • The final expression. A line without a semicolon is the value of the block, so curr on its own is the return value.

    Complexity

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

    Space: O(1). Only prev, curr and ways are stored, however large n is. A table with one entry per step would need O(n).

    Edge cases and common mistakes

    • Starting prev at 0. The ground then has no ways to stand on it, and climb_stairs(2) would return 1 instead of 2.
    • Using 2..n. The loop would run one round too few and return the answer for step n - 1.
    • Updating in the wrong order. Writing curr = ways before prev = curr sets both variables to the same number.
    • Overflow beyond the constraints. The lesson builds with optimizations, where integer overflow wraps silently. climb_stairs(45) returns 1836311903, but climb_stairs(46) returns -1323752223 and climb_stairs(47) returns 512559680. In a debug build the same overflow would panic. That is why the constraints stop at 45; for larger n, use i64 or u64.
    • Counting the same way twice. The two groups, last move of 1 and last move of 2, are disjoint, so adding them is right; no subtraction is needed.

    Testing

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