Challenge - 5 Problems
Climbing Stairs Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Climbing Stairs Function
What is the output of this Rust code that calculates the number of ways to climb 4 stairs using recursion?
DSA Rust
fn climb_stairs(n: i32) -> i32 {
if n <= 2 {
return n;
}
climb_stairs(n - 1) + climb_stairs(n - 2)
}
fn main() {
println!("{}", climb_stairs(4));
}Attempts:
2 left
💡 Hint
Think about the base cases and how the function sums ways for n-1 and n-2 steps.
✗ Incorrect
The function returns the number of ways to climb n stairs by summing ways to climb n-1 and n-2 stairs. For n=4, ways are 5.
❓ Predict Output
intermediateOutput of Iterative Climbing Stairs Function
What is the output of this Rust code that calculates the number of ways to climb 5 stairs using iteration?
DSA Rust
fn climb_stairs(n: i32) -> i32 {
let mut first = 1;
let mut second = 2;
if n == 1 {
return first;
}
if n == 2 {
return second;
}
let mut ways = 0;
for _ in 3..=n {
ways = first + second;
first = second;
second = ways;
}
ways
}
fn main() {
println!("{}", climb_stairs(5));
}Attempts:
2 left
💡 Hint
Iteratively sum the ways to climb previous two steps.
✗ Incorrect
The iterative method sums ways for previous two steps. For n=5, the output is 8.
🔧 Debug
advancedIdentify the Runtime Error in Climbing Stairs Code
What error does this Rust code produce when run, and why?
DSA Rust
fn climb_stairs(n: i32) -> i32 {
if n == 0 {
return 0;
}
if n == 1 {
return 1;
}
climb_stairs(n - 1) + climb_stairs(n - 2)
}
fn main() {
println!("{}", climb_stairs(-1));
}Attempts:
2 left
💡 Hint
Consider what happens when n is negative.
✗ Incorrect
The function calls itself with decreasing n without base case for negative values, causing infinite recursion and stack overflow.
🧠 Conceptual
advancedTime Complexity of Climbing Stairs Recursive Solution
What is the time complexity of the naive recursive solution for the climbing stairs problem with input n?
Attempts:
2 left
💡 Hint
Think about how many calls the recursion makes for each step.
✗ Incorrect
The naive recursion calls itself twice for each n, leading to exponential growth in calls.
🚀 Application
expertNumber of Ways to Climb Stairs with Variable Steps
Given the Rust function below that calculates ways to climb n stairs with steps of size 1, 3, or 5, what is the output for n = 6?
DSA Rust
fn climb_stairs_var(n: usize) -> usize {
let mut dp = vec![0; n + 1];
dp[0] = 1;
for i in 1..=n {
if i >= 1 {
dp[i] += dp[i - 1];
}
if i >= 3 {
dp[i] += dp[i - 3];
}
if i >= 5 {
dp[i] += dp[i - 5];
}
}
dp[n]
}
fn main() {
println!("{}", climb_stairs_var(6));
}Attempts:
2 left
💡 Hint
Use dynamic programming to sum ways from steps 1, 3, and 5 behind current step.
✗ Incorrect
The dp array counts ways to reach each step by summing ways from steps 1, 3, and 5 behind. For n=6, total ways are 8.
