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 the following C++ code when calling
factorial(4)?DSA C++
#include <iostream> int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { std::cout << factorial(4); return 0; }
Attempts:
2 left
💡 Hint
Remember factorial of 0 is 1 and factorial(n) = n * factorial(n-1).
✗ Incorrect
The factorial of 4 is 4 * 3 * 2 * 1 = 24. The base case returns 1 when n is 0.
❓ Predict Output
intermediateOutput of Recursive Sum Function
What is the output of this C++ code when calling
sum(3)?DSA C++
#include <iostream> int sum(int n) { if (n <= 0) return 0; return n + sum(n - 1); } int main() { std::cout << sum(3); return 0; }
Attempts:
2 left
💡 Hint
Sum from 1 to n is n*(n+1)/2.
✗ Incorrect
sum(3) = 3 + sum(2) = 3 + 2 + sum(1) = 3 + 2 + 1 + sum(0) = 3 + 2 + 1 + 0 = 6.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci Function
What error will occur when running this C++ code?
DSA C++
#include <iostream> int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 3); } int main() { std::cout << fibonacci(4); return 0; }
Attempts:
2 left
💡 Hint
Check the recursive calls and base cases carefully.
✗ Incorrect
The function calls fibonacci(n-3) without a base case for n < 0, causing infinite recursion and stack overflow.
🧠 Conceptual
advancedUnderstanding Base Case Importance
Why is the base case essential in a recursive function?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
Without a base case, recursion would continue indefinitely, causing a stack overflow error.
❓ Predict Output
expertOutput of Recursive String Reverse Function
What is the output of this C++ code when calling
reverse("abc")?DSA C++
#include <iostream> #include <string> std::string reverse(const std::string& s) { if (s.empty()) return ""; return reverse(s.substr(1)) + s[0]; } int main() { std::cout << reverse("abc"); return 0; }
Attempts:
2 left
💡 Hint
The function moves the first character to the end after reversing the rest.
✗ Incorrect
The function takes the first character off and appends it after reversing the rest, effectively reversing the string.
