Challenge - 5 Problems
Recursion vs Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Fibonacci Function
What is the output of this TypeScript code that calculates Fibonacci numbers recursively?
DSA Typescript
function fib(n: number): number {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Trace the calls for fib(5): fib(4) + fib(3).
✗ Incorrect
The Fibonacci sequence starts 0,1,1,2,3,5... fib(5) returns 5.
🧠 Conceptual
intermediate1:30remaining
When is Iteration Better Than Recursion?
Which scenario is best suited for iteration instead of recursion?
Attempts:
2 left
💡 Hint
Think about stack limits and performance with large inputs.
✗ Incorrect
Iteration avoids stack overflow and is efficient for simple loops with large inputs.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Factorial
What error will this TypeScript code produce when calculating factorial?
DSA Typescript
function factorial(n: number): number {
if (n === 0) return 1;
return n * factorial(n);
}
console.log(factorial(4));Attempts:
2 left
💡 Hint
Check the recursive call argument.
✗ Incorrect
The function calls factorial(n) instead of factorial(n-1), causing infinite recursion.
❓ Predict Output
advanced2:00remaining
Output of Iterative vs Recursive Sum
What is the output of this TypeScript code that sums numbers from 1 to 5 using iteration and recursion?
DSA Typescript
function sumIterative(n: number): number {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i;
}
return total;
}
function sumRecursive(n: number): number {
if (n === 0) return 0;
return n + sumRecursive(n - 1);
}
console.log(sumIterative(5));
console.log(sumRecursive(5));Attempts:
2 left
💡 Hint
Sum of numbers 1 to 5 is 15.
✗ Incorrect
Both functions correctly calculate the sum 1+2+3+4+5 = 15.
🧠 Conceptual
expert1:30remaining
Why Use Recursion Over Iteration?
Which reason best explains when recursion is preferred over iteration?
Attempts:
2 left
💡 Hint
Think about problem structure and clarity.
✗ Incorrect
Recursion is preferred for problems like tree traversal where the structure fits recursive calls.