Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

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

    KOTLIN · DYNAMIC PROGRAMMING

    Climbing Stairs in Kotlin, explained

    Problem overview

    The function climbStairs receives n, the number of steps in a staircase, and returns the number of distinct ways to climb to the top. Each move is 1 step or 2 steps, and the order of the moves matters: 1 then 2 is a different way from 2 then 1. The constraints say 1 <= n <= 45 and that the answer fits in an Int.

    For n = 3 the three ways are 1+1+1, 1+2 and 2+1, so the answer is 3. For n = 4 there are five ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2.

    Approach: build the answer from the ground up

    Think about the last move. To stand on step i, you came either from step i - 1 with a 1-step move or from step i - 2 with a 2-step move. Those are different last moves, so no way is counted twice, and the number of ways to reach step i is the sum of the two counts below it.

    That is a recurrence, ways(i) = ways(i - 1) + ways(i - 2), and it is the Fibonacci rule. A plain recursive function would recompute the same values again and again, and its running time grows exponentially. Counting from the bottom up computes each value once. Because a value only depends on the previous two, there is no need for an array: two variables are enough.

    The base cases are step 0, the ground, with 1 way (do nothing), and step 1 with 1 way (one 1-step move). Counting the ground as 1 is what makes step 2 come out right: 1 + 1 = 2, the ways 1+1 and 2.

    Step by step

    1. Create prev as a var equal to 1. It holds the ways to be on step 0.
    2. Create curr as a var equal to 1. It holds the ways to reach step 1.
    3. Loop i over 2..n. At the start of each round, curr is the count for step i - 1 and prev is the count for step i - 2.
    4. Add the two counts into a val named ways. This is the count for step i.
    5. Slide the window up one step. Set prev to curr first, then curr to ways. The reverse order would overwrite the value prev needs.
    6. Return curr. After the last round it holds the count for step n.

    Here is the loop for n = 4, printing the two variables at the start of each round:

    i=2 prev=1 curr=1
    i=3 prev=1 curr=2
    i=4 prev=2 curr=3
    end prev=3 curr=5
    

    The last curr, 5, matches the five ways listed above.

    The solution in Kotlin

    class Solution {
    
        fun climbStairs(n: Int): Int {
            var prev = 1
            var curr = 1
            for (i in 2..n) {
                val ways = prev + curr
                prev = curr
                curr = ways
            }
            return curr
        }
    }
    

    The Kotlin details worth a look:

    • var and val. prev and curr are reassigned in every round, so they must be var. ways is created fresh in each round and never changes, so val is right.
    • 2..n is inclusive on both ends. Step n is therefore processed. When n is 1, the range 2..1 is empty, the loop body never runs, and the function returns the initial curr, which is 1. That is the correct answer for one step.
    • The loop variable is a val. i can't be assigned inside the loop.
    • Int is 32 bits. Overflow wraps silently instead of raising an error. For n = 45 the result is 1836311903, which fits. The constraint stops at 45 for this reason: carrying the same loop on to n = 50 wraps around to the negative number -1109825406.
    • The function has a block body with an explicit return. The last expression of a block is not returned automatically in Kotlin, as it would be in some other languages.

    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, ways and the loop counter are stored, however large n is. A table with one entry per step would use O(n).

    Edge cases and common mistakes

    • The smallest input. For n = 1 the answer is 1, because the loop is skipped. Writing the loop as 1..n would add an extra round and return 2.
    • Starting prev at 0. It is tempting to say there are no ways to stand on the ground. Then step 2 gives 0 + 1 = 1 instead of 2, and every later value is wrong.
    • Updating in the wrong order. If curr is changed before prev is set, prev receives the new value and the two counts become equal, so the sequence stops growing as it should.
    • Looping to n - 1 or using until n. The range 2 until n stops one step short, and the function returns the count for step n - 1.
    • Ordered or unordered. The problem counts 1+2 and 2+1 separately. A solution that counts only the number of 2-steps would give a smaller answer for n = 3.

    Testing

    These inputs give the following results from the reference solution:

    • 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.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free