CodeArchon

easy1-D Dynamic ProgrammingAdobeAppleAmazon

Staircase Hopper

A courier counts the number of unique paths up a straight staircase while taking either 1 or 2 steps at a time.

You are climbing a staircase that takes n steps. Each step you can climb 1 or 2 stairs. In how many distinct ways can you reach the top?

Choose approach

?
0
1
1
2
2
?
3
?
4
?
5
?
6
i
1/6
Narrationstep 1 of 6

Base: dp[1]=1, dp[2]=2.

1def climbStairs(n):
2 if n <= 2: return n
3 dp = [0, 1, 2]
4 for i in range(3, n + 1): dp.append(dp[i-1] + dp[i-2])
5 return dp[n]
Variables
n=6

How to think about it

  1. Each step comes from either a 1-hop or 2-hop predecessor.
  2. Fibonacci identity: F(n+1).

Edge cases to catch in interview

  • n = 1 -> 1.
  • n = 2 -> 2.

Examples

Example 13
{"n":3}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed