#70

Climbing Stairs

Easy
MathDynamic ProgrammingMemoizationDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to store the number of ways to reach each step, building up from the base cases. This avoids redundant calculations and reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array dp of size n + 1 to store the number of ways to reach each step.
  2. 2Step 2: Initialize dp[0] = 1 and dp[1] = 1 (base cases).
  3. 3Step 3: Loop from 2 to n, and for each step, set dp[i] = dp[i - 1] + dp[i - 2].
  4. 4Step 4: Return dp[n] as the result.
solution.py8 lines
1def climbStairs(n):
2    if n == 1:
3        return 1
4    dp = [0] * (n + 1)
5    dp[0], dp[1] = 1, 1
6    for i in range(2, n + 1):
7        dp[i] = dp[i - 1] + dp[i - 2]
8    return dp[n]

Complexity note: The time complexity is linear because we compute the number of ways for each step exactly once. The space complexity is also linear due to the dp array.

  • 1The number of ways to reach the nth step can be derived from the sum of the ways to reach the (n-1)th and (n-2)th steps.
  • 2This problem exhibits overlapping subproblems, making it suitable for dynamic programming.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.