Math Fundamentals18 sections · 814 units
Open in Course

Climbing Stairs - Implementation

The pseudocode

Here is the full solution:


function climbStairs(n)
    if n <= 2 then
        return n
    prev2 := 1
    prev1 := 2
    for i from 3 to n
        current := prev1 + prev2
        prev2 := prev1
        prev1 := current
    return prev1

Time: O(n)O(n). Space: O(1)O(1). This is the space-optimized version since you only need the last two values.