Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

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

    SWIFT · DYNAMIC PROGRAMMING

    Climbing Stairs in Swift, explained

    Problem overview

    The method climbStairs receives the number of steps n and returns in how many distinct ways you can climb them, taking 1 or 2 steps at a time. Order counts: 1 step then 2 steps is a different way from 2 steps then 1 step. The constraints are 1 <= n <= 45, and the answer always fits in a 32-bit integer.

    For n = 4 the answer is 5: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. For n = 3 it is 3, and for n = 2 it is 2.

    Approach: build the counts from the bottom up

    Think about the very last move onto step k. It was either a 1-step move from step k - 1 or a 2-step move from step k - 2. These end differently, so they are different ways, and nothing is counted twice. Therefore:

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

    This is the pattern of dynamic programming: a big answer is built from the answers to smaller versions of the same question. A direct recursive function would recompute the same values again and again and take exponential time. Counting from step 2 upward computes each value once.

    Each value depends only on the two before it, so the code doesn't need a whole table. Two variables are enough: prev for the step two below and curr for the step one below. The starting values are both 1. Step 0, the ground, counts as one way (don't move), and step 1 has one way (a single 1-step move). Counting the ground as 1 is what makes step 2 come out as 1 + 1 = 2.

    Here is the loop for n = 5, copied from a real run:

    Stepwaysprev aftercurr after
    2212
    3323
    4535
    5858

    After the last round curr is 8, so there are 8 ways to climb 5 steps. The sequence 1, 2, 3, 5, 8 is the Fibonacci sequence.

    Step by step

    1. Create prev with var, set to 1. It holds the ways to stand on step 0. It uses var because the loop will change it.
    2. Create curr the same way, also 1. It holds the ways to reach step 1. For n = 1 the loop does nothing and curr is already right.
    3. Loop over steps 2 up to n. The range 2..<(n + 1) covers exactly those steps. The body never uses the step number, so the loop variable is _. Write the closing brace right away.
    4. Add the two counts into a let constant named ways. It is the number of ways to reach the step this round is counting. It never changes after that, so let fits.
    5. Slide the window up one step. Set prev to curr first, then curr to ways. With the opposite order, curr would be overwritten before prev could copy it.
    6. Return curr after the loop. It holds the count for step n.

    The solution in Swift

    class Solution {
    
        func climbStairs(_ n: Int) -> Int {
            var prev = 1
            var curr = 1
            for _ in 2..<(n + 1) {
                let ways = prev + curr
                prev = curr
                curr = ways
            }
            return curr
        }
    }
    

    The Swift details worth a closer look:

    • Half-open ranges. 2..<(n + 1) stops before n + 1, so the last value is n. The parentheses make the arithmetic happen first, and the range stays readable. The closed form 2...n would be the same range for n = 2 or more.
    • Ranges can't run backwards. Building a range whose end is below its start stops the program with a run-time error. The half-open 2..<2 is a valid empty range, which is why n = 1 works: the range is 2..<2 and the body never runs. With 2...n and n = 1 the range would be 2...1, which is invalid. The same crash happens for n = 0, which is outside the constraints.
    • for _ in. When the loop variable isn't used, the underscore says so, and the compiler doesn't warn about an unused name.
    • let inside the loop. A new ways constant is created each round. prev and curr live outside the loop and are declared with var, so the loop can assign to them.
    • Overflow traps. A Swift Int is 64 bits, and overflowing it crashes the program instead of wrapping. Here the values stay small: for n = 45 the result is 1836311903.

    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.

    Edge cases and common mistakes

    • n = 1. The loop is skipped and the method returns 1.
    • Starting prev at 0. Then step 2 would come out as 1, not 2. The ground counts as one way.
    • Updating in the wrong order. Writing curr = ways before prev = curr makes both variables equal to ways, and every later sum is wrong.
    • Using 2...n. It crashes for n = 1, as explained above.
    • Plain recursion. climbStairs(n - 1) + climbStairs(n - 2) is correct but recomputes values and becomes far too slow near n = 45.

    Testing

    Try these in the editor above. The results come from running the reference solution:

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