Recursion is when a function solves a problem by calling itself on a smaller version of the same problem, until it reaches a base case simple enough to answer directly. It suits naturally recursive structures such as trees, nested folders and divide and conquer algorithms. Avoid it when the depth could be very large, since each call uses stack space and can overflow, or when naive recursion repeats work that a loop or memoisation would avoid.
Why interviewers ask this
Recursion trips up a lot of students, so the interviewer wants a clear explanation with a base case and a recursive case, plus an example you can trace. They also want judgement about when not to use it: stack depth limits, repeated subproblems and readability. Mentioning memoisation for something like Fibonacci, or that some languages cap recursion depth, shows you have actually run into these problems.
How to structure your answer
- Define recursion with its base case and recursive case.
- Walk through a small example.
- Name problems where recursion fits naturally.
- Explain the limits and the alternatives.
Example answer
Recursion is a function calling itself on a smaller version of the same problem. Every recursive function needs two parts: a base case that can be answered directly, and a recursive case that moves towards it. Factorial is the simplest example. The factorial of one is one, which is the base case, and the factorial of n is n times the factorial of n minus one. Each call waits for the smaller one to finish, and the results multiply back up. It shines with structures that are recursive themselves. For a coursework project I wrote a function to calculate the total size of a folder, and recursion made it simple: a folder's size is the sum of its files plus the size of each subfolder. Tree traversals and merge sort work the same way. I avoid it when the depth could get large, because each call takes stack space, and Python stops at a default limit of about a thousand calls. I also watch for repeated work. Naive recursive Fibonacci recalculates the same values over and over, so I would add memoisation or just use a loop.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- How would you convert a recursive function into a loop?
- What is memoisation, and how does it help?
- What happens on the call stack during a recursive call?
Related software engineering intern questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions