What is Recursion?
When a function calls itself repeatedly until it reaches a specified stopping condition such a function is called a recursive function.
Format of a recursive function
A recursive function consists of two main parts:
- Base Case: The base case is where all further calls to the same function stop, meaning that it does not make any subsequent recursive calls. This is also known as a terminating condition.
- Recursive Case: The recursive case is where the function calls itself repeatedly until it reaches the base case. This is also known as a recurrence relation to solve smaller sub-problems.
Let's understand it by calculating factorial of a number

When to Use Recursion?
The most obvious indication that you should use recursion is when that problem can be broken down into smaller subproblems. It is likely that a problem can be solved using recursion when you observe a pattern of that problem breaking down into similar subproblems.
Look for problems where:
- The problem has a repeating structure
Example: Trees, Folders, Nested Lists, Graphs. - The solution depends on smaller subproblems
Example: Factorial, Fibonacci, Merge Sort. - You need to explore multiple choices
Example: Permutations, Combinations, Subsets, Maze Paths. - The problem involves going deep and coming back
Example: DFS, Backtracking, Tree Traversal. - The input naturally shrinks each time
Example: N - 1, Smaller Array, Left/Right Half, Remaining String
Recursion and Memory Visualisation
When a function is called, its memory is allocated on a stack.
Each program has a reserved region of memory referred to as its stack. When a function executes (a running function), it adds its state data to the top of the stack. When the function exits, this data is removed from the stack.
Let's visualise the code stack of the factorial recursive code:


Similarly,
- factorial(4) will call factorial(3)
- factorial(3) will call factorial(2)
- factorial(2) will call factorial(1)

Now, the activation records will start popping from the stack.





A recursive function calls itself, so the memory for a called function is allocated on top of the memory allocated for calling the function.
Time and Space Complexity
For factorial(5), the function calls happen like this:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
So if N = 5, the function is called 5 times.
Each function call does a small constant amount of work. Hence, time complexity will be O(N).
In this case, for N = 5, the maximum number of function calls that were there on the stack are 5 at a time. Hence, the space complexity will be O(N).
