Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

Climbing Stairs in Scala: 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

    SCALA · DYNAMIC PROGRAMMING

    Climbing Stairs in Scala, explained

    Problem overview

    The method climbStairs 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 either 1 or 2 steps. Order matters: 1 step then 2 is a different way from 2 then 1.

    For n = 4 there are five ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. For n = 3 there are three, and for n = 2 there are two. The constraints say 1 <= n <= 45 and that the answer fits in a 32-bit integer.

    Approach: build up from the ground

    Listing every sequence of moves would work for small n, but the number of sequences grows quickly. A better question is: how many ways are there to stand on step i? The last move onto step i was either a 1-step move from step i - 1 or a 2-step move from step i - 2. Those two groups of ways are different, and together they cover everything, so

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

    This is dynamic programming: each answer reuses two smaller answers. It also means we never need the whole table. To compute step i we only look at the two steps below it, so two variables are enough and the extra space is O(1).

    The starting values are ways(0) = 1 and ways(1) = 1. Step 0 is the ground, and there is exactly one way to be there: don't move. Counting it is what makes step 2 come out as 1 + 1 = 2.

    Step by step

    1. Create prev with var, starting at 1. It holds the ways to reach the step two below the current one, at first the ground.
    2. Create curr the same way, starting at 1. It holds the ways to reach step 1, which is one 1-step move. For n = 1 the loop never runs and this is already the answer.
    3. Loop i over 2 to n. At the start of each round, curr is the count for step i - 1 and prev the count for step i - 2.
    4. Store prev + curr in a val named ways. That is the count for step i.
    5. Shift the window. Set prev to curr, then curr to ways. The order matters: assigning curr first would destroy the value prev needs.
    6. End with curr. After the last round it holds the count for step n.

    The solution in Scala

    class Solution {
    
        def climbStairs(n: Int): Int = {
            var prev = 1
            var curr = 1
            for (i <- 2 to n) {
                val ways = prev + curr
                prev = curr
                curr = ways
            }
            curr
        }
    }
    

    The Scala details worth a closer look:

    • var and val. prev and curr change every round, so they are var. ways is created fresh in each round of the loop and never reassigned, so it is a val.
    • 2 to n includes n. The range 2 until n would stop one step early. When n is 1, 2 to 1 is empty and the loop is skipped.
    • The last expression is the result. The method's final line, curr, is its value, so no return is needed.
    • Int overflow is silent. An Int has 32 bits and wraps around without an error. The constraint n <= 45 keeps the answer in range: climbStairs(45) gives 1836311903. Beyond that range the same code gives wrong numbers, for example climbStairs(46) returns -1323752223 and climbStairs(47) returns 512559680. Switching the variables to Long would extend the range.

    Complexity

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

    Space: O(1). Only prev, curr, ways and the loop index are stored, however large n is. Keeping a full array of counts would be O(n).

    Edge cases and common mistakes

    • n = 1. The loop is skipped and the method returns curr, which is 1.
    • Starting prev at 0. The ground has one way to be on it. With 0, step 2 would come out as 1 instead of 2.
    • Updating in the wrong order. If the loop writes curr = ways and then prev = curr, both variables end up equal to ways. For n = 5 that version returns 16 instead of 8.
    • Using until instead of to. The loop then counts only up to step n - 1 and returns a number that is too small.
    • Overflow beyond the constraint. For n above 45 the result no longer fits in an Int, as shown above.

    Testing

    • n = 1 gives 1.
    • n = 2 gives 2.
    • n = 3 gives 3.
    • n = 4 gives 5.
    • n = 5 gives 8.
    • n = 10 gives 89.
    • n = 45 gives 1836311903.

    The counts 1, 2, 3, 5, 8, 13 are the Fibonacci numbers: each is the sum of the two before it, which is the same rule the loop applies.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free