When the problem itself has a recursive structure, trees, mazes, parsing nested expressions, divide-and-conquer algorithms like merge sort and quicksort. In these cases recursion mirrors the structure of the data and produces dramatically cleaner code than the iterative equivalent (which usually requires an explicit stack). Use a loop when iteration is naturally linear: counting, summing an array, traversing a list, polling a sensor. The cost of recursion is the stack frame per call plus the function-call overhead; for shallow recursion this is negligible, but for very deep cases (10,000+) you risk stack overflow, so prefer a loop or convert to tail-recursive form. The rule of thumb: pick the form that mirrors the problem's structure.
Programming Fundamentals · Interview question
When should you use recursion instead of a loop?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Recursion
A function that calls itself. The base case, the recursive case, the call stack, and the question of when to use recursion vs a loop.