Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive vs Loop Factorial
What is the output of the following C++ code that calculates factorial using recursion and a loop?
DSA C++
#include <iostream> int factorial_recursive(int n) { if (n <= 1) return 1; return n * factorial_recursive(n - 1); } int factorial_loop(int n) { int result = 1; for (int i = 2; i <= n; ++i) { result *= i; } return result; } int main() { std::cout << factorial_recursive(5) << " " << factorial_loop(5) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Both functions calculate factorial of 5, but one uses recursion and the other uses a loop.
✗ Incorrect
Both recursive and loop implementations correctly compute 5! = 120. The output prints both results separated by a space.
🧠 Conceptual
intermediateWhy Recursion is Needed for Tree Traversal
Why is recursion often preferred over loops for traversing tree data structures?
Attempts:
2 left
💡 Hint
Think about how trees branch and how loops handle repeated tasks.
✗ Incorrect
Trees have nested branches. Recursion naturally handles nested calls matching tree depth, while loops require explicit stacks to simulate this.
🔧 Debug
advancedIdentify the Output of Recursive Fibonacci with Memoization
What is the output of this C++ code that calculates Fibonacci numbers using recursion with memoization?
DSA C++
#include <iostream> #include <vector> int fib(int n, std::vector<int>& memo) { if (n <= 1) return n; if (memo[n] != -1) return memo[n]; memo[n] = fib(n - 1, memo) + fib(n - 2, memo); return memo[n]; } int main() { int n = 6; std::vector<int> memo(n + 1, -1); std::cout << fib(n, memo) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8...
✗ Incorrect
fib(6) returns the 6th Fibonacci number (0-based index), which is 8.
❓ Predict Output
advancedOutput of Recursive Function with Multiple Recursive Calls
What is the output of this C++ code that prints numbers using recursion with two recursive calls?
DSA C++
#include <iostream> void printNumbers(int n) { if (n == 0) return; std::cout << n << " "; printNumbers(n - 1); printNumbers(n - 1); } int main() { printNumbers(3); return 0; }
Attempts:
2 left
💡 Hint
Trace the calls carefully: each call prints n, then calls itself twice with n-1.
✗ Incorrect
The function prints n, then calls itself twice with n-1, causing a binary tree of calls. For n=3, output is: 3 2 1 1 2 1 1.
🧠 Conceptual
expertWhy Some Problems Cannot Be Solved Cleanly with Loops Alone
Which of the following best explains why some problems require recursion instead of just loops?
Attempts:
2 left
💡 Hint
Think about problems like parsing nested structures or exploring trees.
✗ Incorrect
Recursion matches problems with nested or self-similar structure naturally. Loops require manual stack or state management to simulate this, making code complex.
