Loading

Quipoin Menu

Learn • Practice • Grow

python / Recursion
interview

Q1. What is recursion in Python?
Recursion is a technique where a function calls itself to solve a problem by breaking it down into smaller subproblems. Each recursive call works on a smaller instance, and there is a base case to stop the recursion. Example:
def factorial(n): if n <= 1: return 1 return n * factorial(n-1)

Q2. What are the advantages and disadvantages of recursion?
Advantages: elegant and intuitive for problems like tree traversal, divide-and-conquer. Disadvantages: can be less efficient due to function call overhead, may cause stack overflow for deep recursion (Python default recursion limit is around 1000). Iteration is often faster.

Q3. What is the base case in recursion?
The base case is the condition that stops the recursion. Without a base case, the recursion would continue indefinitely (causing RecursionError). The base case returns a value directly without making further recursive calls. In factorial, n <= 1 is the base case.

Q4. How can you increase the recursion limit?
Use sys.setrecursionlimit() to increase the maximum recursion depth. Example:
import sys sys.setrecursionlimit(10000)
Be cautious; increasing the limit might cause segmentation faults if too deep.

Q5. What is tail recursion? Is it optimized in Python?
Tail recursion is when the recursive call is the last operation in the function. Python does not optimize tail recursion, so it does not prevent stack overflow. Recursion in Python is generally not optimized for performance, so iterative solutions are preferred for deep recursion.