Example 1
ready- Input
n = 2- Expected
2- Why
- the routes are 1+1 and 2
A staircase looks harmless until you count every route up it.
You face n steps. Each move climbs either 1 step or 2 steps. Return the number of
distinct move sequences that land exactly on the top.
The order of the moves matters: climbing 1, 2 and climbing 2, 1 are two different
ways to reach step 3. A move that passes the top doesn't count.
1 <= n <= 45Hints
Every valid route ends with either a 1-step move or a 2-step move. Where could you have been just before each of those moves?
If ways[i] counts routes to step i, then every route to i comes from
step i - 1 or step i - 2. Add those two counts.
Computing the next count needs only the previous two counts. You don't need to keep the full history.
If each move could climb 1, 2, or 3 steps, how would the recurrence and the amount of stored history change?
Visible cases
n = 22n = 33n = 11Interview signal
From each position, branch into a 1-step move and a 2-step move. Reaching exactly zero remaining steps completes one route; passing the top completes none.
def climb_stairs(n: int) -> int:
def count_routes(remaining: int) -> int:
if remaining == 0:
return 1
if remaining < 0:
return 0
return count_routes(remaining - 1) + count_routes(remaining - 2)
return count_routes(n)The recursion redraws the same smaller climb many times. For example, routes from step 10 are counted once through the step-11 branch and again through the step-12 branch.
Time O(2ⁿ). Space O(n) for the deepest chain of recursive calls.
Dynamic programming (DP) means solving reusable smaller subproblems once. Here are the three pieces of the DP:
ways[i] is the number of routes that land exactly on step i.ways[i] = ways[i - 1] + ways[i - 2], because the final move has
length 1 or 2.ways[0] = 1 and ways[1] = 1. The empty route is the one way to
remain at step 0.That is the Fibonacci recurrence, the rule that each new count is the sum of the previous two. A full array works, but the transition reads only two older values. Rolling variables are a fixed set of variables that replace entries which are no longer needed.
def climb_stairs(n: int) -> int:
two_steps_back = 1 # ways[0]
one_step_back = 1 # ways[1]
for _ in range(2, n + 1):
current = one_step_back + two_steps_back
two_steps_back = one_step_back
one_step_back = current
return one_step_backAfter each loop, the two variables hold the counts for the two steps immediately behind the next one. That invariant makes the discarded history irrelevant.
Time O(n). Space O(1).
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
2