Recursion is a problem-solving technique that breaks a problem into smaller subproblems. In this blog, we will cover the basics of recursion and help you understand this problem-solving concept.
What do you mean by recursion?
Recursion helps us to solve a problem by reducing it to smaller instances of the same problem. In other words, a recursive solution defines a problem in terms of itself.
Recursion comes up in mathematics frequently, where we can find many examples of expressions written in terms of themselves. For example, calculating the value of the nth factorial and the nth Fibonacci numbers is one of the best examples. But recursion is just as much a programming concept!
- Finding the nth Factorial: n! = n * (n - 1)! To calculate n!, we solve the smaller subproblem of finding (n - 1)! using the same factorial function, then multiply its result by n.
- Finding the nth Fibonacci: F(n) = F(n - 1) + F(n - 2). To calculate F(n), solve two smaller subproblems—finding F(n - 1) and F(n - 2)using the same function and then add their results.
Note: Subproblems are smaller versions of the original problem.
How recursion works in real life?
Suppose you are standing in a queue and want to find out how many people are behind you. You can only see the person immediately in front of or behind you, so you can’t look back and count everyone at once. But you can ask the person behind you to help. How can we solve this problem recursively? Here is the idea:
- Ask the person directly behind you how many people are behind them.
- If there is no one behind them, they answer 0.
- Otherwise, they ask the next person behind them the same question.
- When someone receives an answer, they add 1 for themselves and pass the total forward.
- The answer moves along the queue until it reaches you.
For example, if there are three people behind you, the last person answers 0. The person before them adds 1, the next adds 1 again, and you receive 3. This is recursion!
int peopleCount(Person currPerson)
{
if (noOneBehind(currPerson) == true)
return 0
else
{
Person personBehind = currPerson.getBehind()
return 1 + peopleCount(personBehind)
}
}How does recursion works in programming?
In programming, recursion is a function calling itself until a "base condition" is true. In other words, to solve a problem, we solve a problem that is a smaller instance of the same problem and then use the solution to that smaller instance to solve the original problem.
void function(input size)
{
base case
.. .. ...
function(smaller input size) //recursive call
.. .. ...
}
int main()
{
... .. ...
function(input size)
... .. ...
}For a recursive algorithm to work, smaller subproblems must eventually arrive at the base case. In simple words, any recursive algorithm has two parts: the base case and the recursive structure.
Base case
The base case is a terminating condition where a function immediately returns the result. This is the smallest version of the problem for which we already know the solution.
Recursive structure
The recursive structure is an idea to design a solution to a problem via the solution of its smaller sub-problems. We continue calling the same problem for smaller input sizes until we reach the base case.
Steps of problem-solving using recursion
- Define the base case: Think of the smallest version of the problem and write down the solution.
- Define the recursive structure: Assume we have a function to solve a problem of the given input size. Now we need to think: How could we use the problem solution for a smaller input size to solve the problem for the given input size? In other words, how can we combine the solutions of the smaller subproblems to get the solution to the larger problem?
- Combine the base case and the recursive structure to generate a complete solution to the problem.
Ideas to keep in mind while working with recursion
- Our code must cover all valid instances of smaller input sizes.
- We must have a correct base case that makes no recursive calls.
- When we make a recursive call, it should call a smaller instance and progress towards the base case.
- When we have a correct recursive structure and base case, then recursion would solve the problem for us. This is a "recursive leap of faith" where we should not worry about the intermediate steps of the recursive calls.
Basic examples of recursive functions
Calculate the sum of two numbers using recursion
sum(x, y)
= x, if(y == 0)
= 1 + sum (x, y - 1), if(y > 0)Calculate the product of two numbers using recursion
product(x, y)
= 0, if(y == 0)
= sum (x, product(x, y - 1), if(y > 0)Calculate the power of two numbers using recursion
power(x, y)
= 1, if(y == 0)
= product (x, power(x, y - 1), if(y > 0)Understanding recursion via finding nth Factorial
The factorial of a non-negative integer is a multiplication of all integers smaller than or equal to n. For example. the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Recursive structure
According to the mathematical definition of the factorial of n, we can write:
n!
= n * (n - 1) * (n - 2) *….* 2 * 1
= n * (n - 1)!
=> nth factorial = n * (n - 1)th factorialIf we calculate the value of the (n - 1)th factorial, we can easily calculate the value of the nth factorial. It means we can solve the problem of input size n with its smaller problem of the input size (n - 1). In other words, we can solve this problem by using the idea of recursion!
Suppose the function fact(n) and fact(n - 1) return the value of the nth and (n - 1)th factorial, respectively. Then we can write the following recursive structure:
fact(n) = n * fact(n - 1)Base case
In every recursive solution, there must be a terminating condition or base case where our recursion will directly give us results without breaking it again into the sub-problem. If we observe the above recursive structure, then we find the following chain of recursive calls behind the scene.
fact(n)
= n * fact(n - 1)
= n * (n - 1) * fact(n - 2)
... and so on
= n * (n - 1) * (n - 2) * ... * 4 * 3 * 2 * fact(1)
= n * (n - 1) * (n - 2) * ... * 4 * 3 * 2 * 1 * fact(0)The factorial of a negative integer is not defined in the context of natural numbers. So fact(0) is the smallest version of the factorial problem where our recursion will terminate and return the value directly i.e. if n = 0, recursion will return the value 1.
Recursive pseudocode of nth Factorial
factorial(n)
if n == 0
return 1
return n * factorial(n - 1)How recursion works in the background?
If we draw the flow of recursion for the factorial program, one can find this pattern: we are calling fact(0) last but it is returning the value first. Similarly, we are calling fact(n) first but it is returning the value last. Did you find Last In First Out (LIFO) order? Yes, you got it right! Behind the scene, the compiler uses a stack to simulate recursion and deliver the output. We call this stack: Call Stack!
- Order of recursive calls: fact(n) -> fact(n - 1) -> … -> fact(i) -> … -> fact(1) -> fact(0).
- Order of return values: fact(0) -> fact(1) -> … -> fact(i) -> … -> fact(n - 1) -> fact(n).
How does the idea of the call stack work in recursion?
When we compile a recursive program, the compiler allocates a call stack to store the history and details of function calls during recursion. For each function call, the call stack stores a stack frame containing details like the function local variables and where execution should resume after a called function returns.
- A recursive call is added to the stack: When a function calls itself with a smaller input, the program creates a new stack frame and places it on top of the current one. Each call has its own copy of its local variables.
- Earlier calls wait: The calls that made the recursive calls pause while the newer calls run. This continues until a call reaches the base case, which stops the recursion.
- The calls finish in reverse order: The base case returns a value and its stack frame is removed. The previous call resumes, uses the returned value and then returns a value to its caller. This continues until the original call finishes.
Visualisation for calculating fact(5) using recursion
Examples of some famous recursive algorithms
Reverse an array
- Recursive structure: reverse (A[], l, r) = swap(A[l], A[r]) + reverse(A, l + 1, r - 1).
- Base case: if (l >= r) then return.
- Recurrence relation: T(n) = T(n - 2) + c, Time complexity = O(n).
Finding the GCD of two numbers
- Recursive structure: GCD(a, b) = GCD(b, a mod b), here a > b.
- Base case: GCD(a, 0) = a.
- Recurrence relation: T(n) = T(n/d) + c, where d is a decreasing factor, Time complexity = O(log b).
Finding the nth Fibonacci
- Recursive structure: fib(n) = fib(n - 1) + fib(n - 2).
- Base case: We have 2 base cases: fib(0) = 0 and fib(1) = 1.
- Recurrence relation: T(n) = T(n - 1) + T(n - 2) + c, Time complexity = O(2^n).
Tower of Hanoi problem
Recursive structure: We move a stack of n disks from peg X to Y using peg Z
- Move top n - 1 disks from X to Z
- Move bottom disk from X to Y
- Move top n - 1 disks from Z peg to YBase case: If n = 1, move disk from X to Y.
Recurrence relation: T(n) = 2 T(n - 1) + c, Time complexity = O(2^n).
Binary Search Algorithm
Recursive structure
binarySearch(A[], l, r, k)
- if A[mid] = k, return mid
- if (A[mid] > k), binarySearch(A[], l, mid - 1, k)
- if (A[mid] < k), binarySearch(A[], mid + 1, r, k)Base case: If (l > r) then return -1.
Recurrence relation: T(n) = T(n/2) + c, Time complexity = O(log n).
Merge Sort Algorithm
Recursive structure
mergeSort (A[], l, r)
- mergeSort(A, l, mid)
- mergeSort(A, mid+1, r)
- merge(A, l, mid, r)Base case: if (l == r) then return. This is a case of a single-element array.
Recurrence relation: T(n) = 2 T(n/2) + cn, Time complexity = O(nlogn).
Quick Sort Algorithm
Recursive structure
quickSort(A[], l, r)
- pivot = partition(A, l, r)
- quickSort(A, l, pivot - 1)
- quickSort(A, pivot + 1, r)Base case: if (l >= r) then return.
Recurrence relation: T(n) = Sum (i = 0 to n - 1) [T(i) + T(n - i - 1)]/ n, Time complexity = O(nlogn) [Average case analysis].
Reverse a Linked List
Recursive structure
reverseList(Node head)
- Node remaining = reverseList(head->next)
- head->next->next = head
- head->next = NULL
- return remainingBase case: if (head == NULL || head->next == NULL), return head.
Recurrence relation: T(n) = T(n - 1) + c, Time complexity = O(n).
Post-order Traversal of a Binary Tree
Recursive structure
postorder(root)
- postorder(root->left)
- postorder(root->right)
- Visit the rootBase case: if(root == NULL), then return.
Recurrence relation: T(n) = T(n - 1) + c, Time complexity = O(n).
Print all permutation of a given string
Recursive structure
permute(S[], l, r)
=>
for(i = l to r)
{
swap(S[l], S[i])
permute(S, l + 1, r)
swap(S[l], S[i])
}Base case: if(l == r) then print(A).
Recurrence relation: T(n) = sum (i = 0 to n - 1) [T(n - i) + c], Time complexity = O(n!).
Stack overflow error in recursion
When a function calls itself, the program stores details like the function arguments, local variables and return address in the call stack. Each recursive call adds another stack frame. But the call stack has a limited size. If recursion continues too deeply, the program can run out of stack space and encounter a stack overflow error. Popular reasons for stack overflow are:
- A missing base case: The function never reaches a condition that stops the recursion.
- An incorrect base case or recursive step: The function fails to reach the base case.
Note: Some compilers can optimise certain tail-recursive functions by reusing the current stack frame instead of adding a new one. This is called tail-call optimisation, but it is not guaranteed in every language or compiler.
Common mistakes in recursive implementations
Here are two common ways that a recursive implementation can go wrong:
- The base case is missing entirely, or the problem needs more than one base case, but not all the base cases are covered.
- The recursive step doesn’t reduce to a smaller subproblem, so the recursion doesn’t converge.
Look for these when you are debugging. A buggy recursive program fails faster!
Analysis of recursive algorithms
The basic idea of recursion analysis: Calculate the total number of operations performed by recursion at each recursive call and do the sum to get the overall time complexity. So, when recursion is doing constant operation at each recursive call, we just count the total number of recursive calls. Otherwise, analysis will be a little mathematical if the operation count at each recursive call is not constant.
There are several techniques to analyse recursion: Substitution method, Recursion tree method and Master theorem.
- The recursion tree method is one of the most popular and fundamental approaches to analysis, where we define recurrence relation, draw a recursion tree, calculate the cost of each level, and do level by level sum to get the overall time complexity.
- The substitution method is a simple idea: We write the recurrence relation function in terms of input size and substitute the value for a smaller input size to get a mathematical series in terms of n. This method works best for some simple recursive functions, but mathematical series can be complex to calculate for some functions.
- The master theorem is one of the most popular techniques which can only be applied to analyze divide and conquer algorithms.
Explore this blog to learn recursion analysis: Analysis of Recursion in data structure and algorithms
Recursion Vs. Iteration
- Both iteration and recursion perform the repeated execution of instructions.
- Both have a termination condition: iteration terminates when the loop condition becomes false, while recursion terminates when it reaches the base case.
- Both can result in infinite repetition: an infinite loop occurs when the loop condition is always true, while infinite recursion occurs when each recursive call fails to move closer to the base case.
- Recursion repeatedly calls a method on smaller problems, which creates method-call overhead. This can consume processor time and memory.
Explore this blog for more details: Iteration vs Recursion comparison
Application of recursion in problem-solving
- Divide and conquer approach
- Solving searching and sorting algorithms
- Solving dynamic programming problems
- Problem-solving using Backtracking
- Solving tree and graph problems using DFS
Concepts to explore further
- Types of recursion
- Tail recursion and recursive optimization
- The idea of functional programming
Coding problems to practice using recursion
- Josephus problem
- Quick-select algorithm to find the kth smallest element
- Recursive binary tree traversals
- Find all possible combinations of K numbers from 1 to n
- Find kth smallest element of two sorted arrays
- Median of two sorted arrays
- Flood fill problem
- N-Queen problem
- Karatsuba algorithm
Content references
- Algorithms by CLRS
- The Algorithm Design Manual by Steven Skiena
If you have any queries/doubts/feedback, please write us at contact@enjoyalgorithms.com. Enjoy learning, Enjoy algorithms!

