Recursion Concept and Call Stack Visualization in DSA C# - Time & Space Complexity
We want to understand how the time taken by a recursive function grows as the input size increases.
How many times does the function call itself and what does that mean for performance?
Analyze the time complexity of the following code snippet.
int Factorial(int n) {
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
This code calculates the factorial of a number using recursion by calling itself with a smaller number each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The recursive call to
Factorial(n - 1)is the repeating operation. - How many times: It repeats once for each number from
ndown to 1, sontimes.
Each time the function calls itself, it does one multiplication and one smaller call until it reaches 1.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 multiplications and calls |
| 100 | About 100 multiplications and calls |
| 1000 | About 1000 multiplications and calls |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time taken grows in a straight line with the size of the input number.
[X] Wrong: "Recursion always makes the code slower by a lot because it repeats too many times."
[OK] Correct: In this case, recursion repeats exactly as many times as needed, no more. It is just like a loop running n times, so the time grows linearly, not exponentially.
Understanding how recursion grows helps you explain your code clearly and shows you can think about performance, which is a valuable skill in interviews.
"What if we changed the recursion to call itself twice each time, like in a Fibonacci sequence? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursion stopping condition
A recursive function must have a base case to stop calling itself; otherwise, it keeps calling endlessly.Step 2: Effect of missing base case
Without a base case, the function calls stack up until memory runs out, causing a stack overflow error.Final Answer:
It causes an infinite loop leading to a stack overflow error -> Option CQuick Check:
Missing base case = infinite recursion [OK]
- Assuming recursion stops automatically
- Confusing recursion with loops
- Thinking recursion runs only once without base case
Solution
Step 1: Check base case correctness
Factorial base case is when n == 0, return 1; this matches int Factorial(int n) { if (n == 0) return 1; else return n * Factorial(n - 1); } only.Step 2: Check recursive call correctness
Recursive call must reduce n by 1 and multiply; int Factorial(int n) { if (n == 0) return 1; else return n * Factorial(n - 1); } does this correctly.Final Answer:
int Factorial(int n) { if (n == 0) return 1; else return n * Factorial(n - 1); } -> Option AQuick Check:
Base case n==0 and n*Factorial(n-1) [OK]
- Using wrong base case value
- Increasing n instead of decreasing
- Returning 0 instead of 1 in base case
static void PrintNumbers(int n) {
if (n == 0) return;
Console.Write(n + " ");
PrintNumbers(n - 1);
}
PrintNumbers(3);Solution
Step 1: Trace the recursive calls
PrintNumbers(3) prints 3, then calls PrintNumbers(2), prints 2, calls PrintNumbers(1), prints 1, then calls PrintNumbers(0) which returns.Step 2: Collect printed output
Printed numbers are 3, 2, 1 in that order, each followed by a space.Final Answer:
3 2 1 -> Option DQuick Check:
Print then recurse = descending order [OK]
- Assuming print happens after recursion
- Including 0 in output
- Confusing order of prints
void PrintUp(int n) {
if (n == 0) return;
PrintUp(n - 1);
Console.Write(n + " ");
}
PrintUp(-1);Solution
Step 1: Analyze base case condition
Base case stops recursion when n == 0, but if n starts negative, it never reaches 0.Step 2: Effect of negative input
Calling PrintUp(-1) causes infinite recursion because n keeps decreasing and never hits 0.Final Answer:
Infinite recursion because negative n never reaches 0 -> Option AQuick Check:
Base case unreachable with negative input [OK]
- Assuming negative input is handled
- Thinking syntax or Console.Write causes error
- Ignoring infinite recursion possibility
int Sum(int n) {
if (n <= 0) return 0;
return n + Sum(n - 1);
}What is the output of
Sum(4) and how many times is the method called?Solution
Step 1: Calculate Sum(4) step-by-step
Sum(4) = 4 + Sum(3), Sum(3) = 3 + Sum(2), Sum(2) = 2 + Sum(1), Sum(1) = 1 + Sum(0), Sum(0) = 0. So total = 4+3+2+1+0 = 10.Step 2: Count method calls
Calls happen for n=4,3,2,1,0 totaling 5 calls.Final Answer:
Output: 10, Method calls: 5 -> Option BQuick Check:
Sum 1 to 4 = 10; calls = n+1 [OK]
- Counting calls as n instead of n+1
- Calculating sum incorrectly
- Ignoring base case call
Ready to prove it?
Pass the test and this pattern moves unknown
