Challenge - 5 Problems
Recursion vs Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive vs Iterative Factorial
What is the output of the following Rust code that calculates factorial using recursion and iteration?
DSA Rust
fn factorial_recursive(n: u32) -> u32 {
if n == 0 { 1 } else { n * factorial_recursive(n - 1) }
}
fn factorial_iterative(n: u32) -> u32 {
let mut result = 1;
for i in 1..=n {
result *= i;
}
result
}
fn main() {
let rec = factorial_recursive(5);
let iter = factorial_iterative(5);
println!("Recursive: {} Iterative: {}", rec, iter);
}Attempts:
2 left
💡 Hint
Recall factorial of 5 is 5*4*3*2*1 = 120
✗ Incorrect
Both recursive and iterative functions correctly compute factorial of 5 as 120.
🧠 Conceptual
intermediateWhen is recursion preferred over iteration?
Which scenario best explains when recursion is preferred over iteration?
Attempts:
2 left
💡 Hint
Think about problems like exploring branches of a tree.
✗ Incorrect
Recursion is ideal for problems like tree traversal where the problem breaks down into similar subproblems.
❓ Predict Output
advancedStack Overflow Risk in Recursion
What error or output will this Rust code produce when called with n = 100000?
DSA Rust
fn recursive_sum(n: u32) -> u32 {
if n == 0 { 0 } else { n + recursive_sum(n - 1) }
}
fn main() {
let result = recursive_sum(100000);
println!("Sum: {}", result);
}Attempts:
2 left
💡 Hint
Consider how deep the recursion goes and Rust's stack limits.
✗ Incorrect
Rust does not optimize tail recursion, so deep recursion causes stack overflow.
🧠 Conceptual
advancedIteration Advantage in Large Data Processing
Why is iteration often better than recursion for processing large data sets in Rust?
Attempts:
2 left
💡 Hint
Think about memory usage and stack size.
✗ Incorrect
Iteration uses loops and constant stack space, so it handles large data without crashing.
🚀 Application
expertChoosing Recursion or Iteration for Fibonacci
Given the task to compute the 40th Fibonacci number efficiently in Rust, which approach is best and why?
Attempts:
2 left
💡 Hint
Consider time complexity and stack limits for large Fibonacci numbers.
✗ Incorrect
Simple recursion is exponential and slow; iteration is efficient and safe for large inputs.
