EvalFrame Technical Mock Interviews & Coding Practice

Climbing Stairs

Easy · Dynamic Programming · Algorithm problem · all problems

You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? **Constraints:** - 1 <= n <= 45 **Examples:** ```typescript climbStairs(2) // 2 (1+1, or 2) climbStairs(3) // 3 (1+1+1, 1+2, 2+1) climbStairs(4) // 5 ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(n)
  • Space complexity: O(1)

We loop from step 3 up to n once. Each step only requires adding the previous two numbers (Fibonacci sequence), executing in O(n) linear time.

Follow-Up Questions Interviewers Ask About Climbing Stairs

  • Why is the naive recursive solution (climbStairs(n-1) + climbStairs(n-2)) considered unacceptable in interviews?
    The naive recursive approach recalculates the same overlapping subproblems exponentially, resulting in O(2^n) time complexity which will freeze or crash for n > 40.
  • How would you adapt the solution if you could take 1, 2, or 3 steps at a time?
    The recurrence relation becomes ways(n) = ways(n-1) + ways(n-2) + ways(n-3) (Tribonacci sequence). You maintain three rolling variables instead of two in O(n) time and O(1) space.
  • Can you compute this in O(log n) time?
    Yes! Using Matrix Exponentiation on the Fibonacci transition matrix [[1, 1], [1, 0]], you can compute the n-th Fibonacci number in O(log n) time.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.