Challenge - 5 Problems
Recursion Mastery
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 that calculates factorial using recursion?
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
Recall factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The factorial function multiplies n by factorial of n-1 until n is 0. factorial(4) = 4*3*2*1 = 24.
❓ Predict Output
intermediateOutput of Recursive Fibonacci Function
What is the output of this Rust code that calculates the 5th Fibonacci number using recursion?
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(5));
}Attempts:
2 left
💡 Hint
Fibonacci sequence starts 0,1,1,2,3,5,...
✗ Incorrect
The 5th Fibonacci number (0-based) is 5: fibonacci(5) = fibonacci(4) + fibonacci(3) = 3 + 2 = 5.
❓ Predict Output
advancedOutput of Recursive Sum of Array Elements
What is the output of this Rust code that recursively sums elements of an array slice?
DSA Rust
fn sum_slice(arr: &[i32]) -> i32 {
if arr.is_empty() {
0
} else {
arr[0] + sum_slice(&arr[1..])
}
}
fn main() {
let numbers = [2, 4, 6, 8];
println!("{}", sum_slice(&numbers));
}Attempts:
2 left
💡 Hint
Sum all elements: 2 + 4 + 6 + 8.
✗ Incorrect
The function adds the first element and recursively sums the rest. Total is 2+4+6+8=20.
❓ Predict Output
advancedOutput of Recursive String Reverse Function
What is the output of this Rust code that reverses a string recursively?
DSA Rust
fn reverse_string(s: &str) -> String { if s.is_empty() { String::new() } else { let (first, rest) = s.split_at(1); format!("{}{}", reverse_string(rest), first) } } fn main() { println!("{}", reverse_string("rust")); }
Attempts:
2 left
💡 Hint
The function moves first character to the end recursively.
✗ Incorrect
The function takes first character and appends it after reversing the rest, so "rust" becomes "tsur".
❓ Predict Output
expertOutput of Recursive Tower of Hanoi Moves
What is the output of this Rust code that prints moves to solve Tower of Hanoi for 3 disks?
DSA Rust
fn tower_of_hanoi(n: u32, from: char, to: char, aux: char) { if n == 1 { println!("Move disk 1 from {} to {}", from, to); } else { tower_of_hanoi(n - 1, from, aux, to); println!("Move disk {} from {} to {}", n, from, to); tower_of_hanoi(n - 1, aux, to, from); } } fn main() { tower_of_hanoi(3, 'A', 'C', 'B'); }
Attempts:
2 left
💡 Hint
Follow the recursive pattern: move n-1 disks to auxiliary, move largest disk, then move n-1 disks to target.
✗ Incorrect
The Tower of Hanoi solution for 3 disks follows a specific sequence of moves as shown in option C.
