Challenge - 5 Problems
Recursion Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Factorial Function
What is the output of this Rust code when calling
factorial(4)?DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(4));
}Attempts:
2 left
💡 Hint
Remember factorial of 0 is 1, and factorial(n) = n * factorial(n-1).
✗ Incorrect
The function calculates factorial recursively. factorial(4) = 4 * 3 * 2 * 1 = 24.
❓ Predict Output
intermediateOutput of Recursive Sum Function
What is printed when the following Rust code runs
sum(3)?DSA Rust
fn sum(n: u32) -> u32 { if n == 0 { 0 } else { n + sum(n - 1) } } fn main() { println!("{}", sum(3)); }
Attempts:
2 left
💡 Hint
Sum of numbers from 1 to n is n*(n+1)/2.
✗ Incorrect
sum(3) = 3 + 2 + 1 + 0 = 6.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci Function
What error occurs when running this Rust code?
DSA Rust
fn fibonacci(n: u32) -> u32 {
if n == 0 {
0
} else if n == 1 {
1
} else {
fibonacci(n - 1) + fibonacci(n - 2)
}
}
fn main() {
println!("{}", fibonacci(42));
}Attempts:
2 left
💡 Hint
Think about how many times fibonacci calls itself for large n.
✗ Incorrect
The recursive calls grow exponentially causing stack overflow for large n like 42.
🧠 Conceptual
advancedBase Case Importance in Recursion
Why is the base case essential in a recursive function?
Attempts:
2 left
💡 Hint
Without base case, recursion never ends.
✗ Incorrect
Base case stops recursion by providing a condition to end recursive calls.
🚀 Application
expertOutput of Recursive String Reversal
What is the output of this Rust code when reversing the string
"rust"?DSA Rust
fn reverse(s: &str) -> String { if s.is_empty() { String::new() } else { let (first, rest) = s.split_at(1); format!("{}{}", reverse(rest), first) } } fn main() { println!("{}", reverse("rust")); }
Attempts:
2 left
💡 Hint
The function moves the first character to the end recursively.
✗ Incorrect
The function reverses the string by recursively moving first character to the end.
