Challenge - 5 Problems
Climbing Stairs Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of climbing stairs with 3 steps
What is the output of the following code that calculates the number of ways to climb 3 stairs if you can take 1 or 2 steps at a time?
DSA Python
def climb_stairs(n): if n <= 2: return n dp = [0] * (n + 1) dp[1], dp[2] = 1, 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] print(climb_stairs(3))
Attempts:
2 left
💡 Hint
Think about how many ways you can reach step 3 by taking 1 or 2 steps.
✗ Incorrect
For 3 steps, you can climb as: (1,1,1), (1,2), (2,1) which totals 3 ways.
❓ Predict Output
intermediateNumber of ways to climb 5 stairs
What will be printed by this code that calculates ways to climb 5 stairs with steps of 1 or 2?
DSA Python
def climb_stairs(n): if n <= 2: return n dp = [0] * (n + 1) dp[1], dp[2] = 1, 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] print(climb_stairs(5))
Attempts:
2 left
💡 Hint
Use the relation dp[i] = dp[i-1] + dp[i-2] starting from dp[1]=1 and dp[2]=2.
✗ Incorrect
dp[3]=3, dp[4]=5, dp[5]=8. The code returns dp[5] which is 8, but option A is 5, so check carefully.
❓ Predict Output
advancedOutput of recursive climbing stairs with memoization for 4 steps
What is the output of this recursive function with memoization when called with n=4?
DSA Python
def climb_stairs(n, memo={}): if n in memo: return memo[n] if n <= 2: memo[n] = n return n memo[n] = climb_stairs(n-1, memo) + climb_stairs(n-2, memo) return memo[n] print(climb_stairs(4))
Attempts:
2 left
💡 Hint
Remember the base cases and how memoization stores results.
✗ Incorrect
For n=4, ways = ways(3) + ways(2) = 3 + 2 = 5.
🔧 Debug
advancedIdentify the error in climbing stairs code
What error will this code produce when run?
DSA Python
def climb_stairs(n): dp = [0] * n dp[1] = 1 dp[2] = 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] print(climb_stairs(3))
Attempts:
2 left
💡 Hint
Check the size of the dp list and the indices used.
✗ Incorrect
dp list has size n=3, so indices 0,1,2 are valid. dp[2] = 2 is okay, but dp[3] access in loop causes IndexError.
🚀 Application
expertNumber of ways to climb stairs with 1, 2, or 3 steps
What is the output of this code that calculates ways to climb 4 stairs if you can take 1, 2, or 3 steps at a time?
DSA Python
def climb_stairs(n): if n == 0: return 1 dp = [0] * (n + 1) dp[0] = 1 for i in range(1, n + 1): dp[i] += dp[i - 1] if i - 1 >= 0 else 0 dp[i] += dp[i - 2] if i - 2 >= 0 else 0 dp[i] += dp[i - 3] if i - 3 >= 0 else 0 return dp[n] print(climb_stairs(4))
Attempts:
2 left
💡 Hint
Count all ways to reach step 4 using 1, 2, or 3 steps.
✗ Incorrect
Ways to climb 4 steps with 1,2,3 steps are 7: (1,1,1,1), (1,1,2), (1,2,1), (2,1,1), (2,2), (1,3), (3,1).
