Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Factorial Function
What is the output of the following C code when calling
factorial(4)?DSA C
int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { int result = factorial(4); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
Recall that factorial of n is n multiplied by factorial of n-1, with factorial(0) = 1.
✗ Incorrect
The factorial function multiplies numbers from n down to 1 recursively. factorial(4) = 4 * 3 * 2 * 1 = 24.
❓ Predict Output
intermediate2:00remaining
Output of Recursive Sum Function
What will be printed after executing this C code snippet?
DSA C
int sum(int n) { if (n <= 0) return 0; return n + sum(n - 1); } int main() { printf("%d", sum(5)); return 0; }
Attempts:
2 left
💡 Hint
Sum of first n natural numbers is n*(n+1)/2.
✗ Incorrect
The function adds numbers from 5 down to 1 recursively: 5+4+3+2+1=15.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Fibonacci Function
What error will occur when running this C code?
DSA C
int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int result = fibonacci(-1); printf("%d", result); return 0; }
Attempts:
2 left
💡 Hint
Consider what happens when n is negative in the recursive calls.
✗ Incorrect
The function does not handle negative input, so calls fibonacci(-1), fibonacci(-2), etc., causing infinite recursion and stack overflow.
🧠 Conceptual
advanced2:00remaining
Call Stack Depth in Recursive Function
If a recursive function calls itself with n-1 until n reaches 0, what is the maximum depth of the call stack when called with n=7?
Attempts:
2 left
💡 Hint
Count the initial call plus all recursive calls until base case.
✗ Incorrect
The call stack includes the initial call plus one call for each decrement until 0, so total 8 calls.
🚀 Application
expert3:00remaining
Output of Recursive String Reverse Function
What is the output of this C program that reverses a string recursively?
DSA C
#include <stdio.h> #include <string.h> void reverse(char *str, int start, int end) { if (start >= end) return; char temp = str[start]; str[start] = str[end]; str[end] = temp; reverse(str, start + 1, end - 1); } int main() { char s[] = "hello"; reverse(s, 0, strlen(s) - 1); printf("%s", s); return 0; }
Attempts:
2 left
💡 Hint
The function swaps characters from start and end moving inward.
✗ Incorrect
The function swaps first and last characters recursively until the middle is reached, reversing the string.