DSA · Patterns, not puzzles
What makes a recursive function correct?
Short answer
A correct recursive function has a base case that stops the recursion and a recursive step that moves strictly closer to that base case. Without both, it either returns the wrong result or overflows the stack.
Recursion is a way to express a problem in terms of a smaller version of itself. The base case handles the smallest input directly. The recursive case assumes the smaller call is correct and combines its result. That assumption is the inductive step.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
function sum(values, index = 0) {
if (index === values.length) return 0;
return values[index] + sum(values, index + 1);
}What to check
- Does every branch eventually reach a base case?
- Does the recursive argument strictly shrink?
- Does the base case cover empty and single-element inputs?
- Is the recursion depth safe for the expected input size?
- Are you recomputing the same subproblems? If so, memoize or use a loop
The call stack is finite. A recursion depth of tens of thousands can overflow in JavaScript. Tail calls are not reliably optimized, so a loop is often safer for deep linear recursion.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if a recursive function never reaches its base case?
- 2How deep can recursion go in JavaScript?
- 3When should you convert recursion to iteration?
- 4How does memoization fit into recursion?
Say it in the interview
A recursive function needs a base case that returns without calling itself and a recursive step that makes the problem strictly smaller. If either is missing, it will not terminate or will produce an incomplete result. I also check the empty and single-element cases and the maximum call depth. If the same subproblems repeat, I add memoization or rewrite it as a loop.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.