Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

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

    TYPESCRIPT · DYNAMIC PROGRAMMING

    Climbing Stairs in TypeScript, explained

    Problem overview

    The method climbStairs(n: number): number receives the number of steps in a staircase and returns how many distinct ways there are to reach the top. Each move climbs 1 or 2 steps, and the order of the moves matters: 1 then 2 and 2 then 1 are two different ways.

    For n = 4 there are five ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. The method returns 5. The constraints say n is between 1 and 45 and that the answer always fits in a 32-bit integer.

    Approach: build the counts from the bottom up

    Listing every way works for 4 steps, but the number of ways grows quickly, so the code has to count without listing. The key observation is about the last move. To stand on step i, you arrived either from step i - 1 with a 1-step move or from step i - 2 with a 2-step move. Those two groups never overlap, because their last moves differ, and together they cover every way. So:

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

    This is the Fibonacci recurrence. Writing it as a plain recursive function would recompute the same values over and over and take exponential time. Dynamic programming avoids that by solving the small cases first and reusing their answers. Here each answer depends only on the two before it, so there is no need for a whole table: two variables are enough.

    The starting values are ways(0) = 1 and ways(1) = 1. Step 0 is the ground, and there is exactly one way to be on it: don't move. Counting it makes step 2 come out right, since 1 + 1 = 2 (either two 1-steps or one 2-step).

    Step by step

    1. Create prev with let, starting at 1. It holds the ways to reach the step two below the current one, starting with the ground.
    2. Create curr the same way, also 1. It holds the ways to reach step 1. For n = 1 the loop never runs, so this value is already the answer.
    3. Loop with i from 2 up to and including n. Use <=: step n is the top and needs its own count. 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 const named ways. That is the count for step i.
    5. Slide the window up one step. Set prev = curr first, then curr = ways. Doing it the other way around would overwrite the value prev still needs.
    6. Return curr. After the last round it holds the count for step n.

    Here is what the variables hold for n = 5:

    start  prev=1 curr=1
    i=2    ways=2 prev=1 curr=2
    i=3    ways=3 prev=2 curr=3
    i=4    ways=5 prev=3 curr=5
    i=5    ways=8 prev=5 curr=8

    The function returns 8. The values 1, 2, 3, 5, 8 are the answers for 1 to 5 steps, so you can check them against the examples above.

    The solution in TypeScript

    class Solution {
    
        climbStairs(n: number): number {
            let prev = 1;
            let curr = 1;
            for (let i = 2; i <= n; i++) {
                const ways = prev + curr;
                prev = curr;
                curr = ways;
            }
            return curr;
        }
    }
    

    The TypeScript details worth knowing:

    • Inferred types. let prev = 1 needs no annotation: TypeScript infers number from the initial value. The same goes for ways, which is number because both operands are.
    • let versus const. prev and curr change in every round, so they need let. ways is created fresh in each round and never reassigned, so const fits, and its scope ends with the loop body.
    • No integer overflow, but limits. number is a double, so nothing wraps around. The result is still exact only up to 2**53. The answers for n = 45 and n = 46 are 1836311903 and 2971215073. The second no longer fits in a signed 32-bit integer, but in TypeScript it is still exact; the constraint n <= 45 comes from languages with a 32-bit int. Far beyond that, precision goes: climbStairs(80) gives 37889062373143900, which is not the true value.
    • The return annotation. : number after the parameter list is erased when the code compiles to JavaScript. It documents the contract and lets the compiler check the return, but it does nothing at run time.

    Complexity

    Time: O(n). The loop runs n - 1 times and each round does a constant amount of work. The naive recursion without reuse takes exponential time, because it solves the same sub-staircases again and again.

    Space: O(1). Only prev, curr, ways and i exist, no matter how large n is. A table of n + 1 counts would also work and would cost O(n) space.

    Edge cases and common mistakes

    • n = 1. The loop condition 2 <= 1 is false from the start, so the function returns the initial curr, which is 1.
    • n = 2. One round runs: ways = 1 + 1 = 2. This is why prev starts at 1 and not 0.
    • Using < in the loop. The function would stop one step short and return the count for n - 1. For n = 3 it would return 2 instead of 3.
    • Updating in the wrong order. Setting curr = ways before prev = curr makes both variables equal, and the counts stop growing correctly.
    • Counting combinations instead of sequences. The order of moves matters here, so 1+2 and 2+1 both count. That is why the two groups of ways add instead of being merged.
    • n = 0. It is outside the constraints. The function would return 1, matching the idea of one way to stay on the ground.

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