Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a recursive function that counts down from n to 1.
DSA Rust
fn countdown(n: i32) {
if n == 0 {
return;
}
println!("{}", n);
countdown([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using 0 always stops immediately without counting down.
✗ Incorrect
The function calls itself with n - 1 to count down until it reaches zero.
2fill in blank
mediumComplete the code to calculate factorial of n recursively.
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial([1])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using 0 or 1 directly in recursive call breaks logic.
✗ Incorrect
Factorial multiplies n by factorial of n - 1 until it reaches 0.
3fill in blank
hardFix the error in the recursive Fibonacci function to correctly compute fib(n).
DSA Rust
fn fib(n: u32) -> u32 {
if n == 0 || n == 1 {
n
} else {
fib([1]) + fib(n - 2)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n - 3 skips needed Fibonacci terms.
✗ Incorrect
Fibonacci is sum of fib(n-1) and fib(n-2).
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from 1 to n.
DSA Rust
fn sum_to_n(n: u32) -> u32 {
if n == 0 {
[1]
} else {
n + sum_to_n([2])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 in base case causes off-by-one error.
Using n + 1 in recursive call causes infinite recursion.
✗ Incorrect
Base case returns 0; recursive call sums n with sum_to_n(n - 1).
5fill in blank
hardFill all three blanks to create a recursive function that reverses a string slice.
DSA Rust
fn reverse(s: &str) -> String {
if s.is_empty() {
[1]
} else {
let (first, rest) = s.split_at(1);
reverse([2]) + first
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning s in base case causes infinite recursion.
Using &s[1..] instead of &rest is correct but less clear here.
✗ Incorrect
Base case returns empty string; recursive call reverses rest and adds first char.
