Recursion
Recursion
Step1 - Define a base case: Identify the simplest case for which the
solution is known or trivial. This is the stopping condition for the
recursion, as it prevents the function from infinitely calling
itself.
Step3 - Ensure the recursion terminates: Make sure that the recursive
function eventually reaches the base case, and does not enter an
infinite loop.
step4 - Combine the solutions: Combine the solutions of the
subproblems to solve the original problem.
A Mathematical Interpretation
Let us consider a problem that a programmer has to determine the sum of first
n natural numbers, there are several ways of doing that but the simplest
approach is simply to add the numbers starting from 1 to n. So the function
simply looks like this,
approach(1) – Simply adding one by one
f(n) = 1 + 2 + 3 +……..+ n
but there is another mathematical approach of representing this,
approach(2) – Recursive adding
f(n) = 1 n=1
f(n) = n + f(n-1) n>1
There is a simple difference between the approach (1) and approach(2) and
that is in approach(2) the function “ f( ) ” itself is being called inside the
function, so this phenomenon is named recursion, and the function containing
recursion is called recursive function, at the end, this is a great tool in the hand
of the programmers to code some problems in a lot easier and efficient way.
How are recursive functions stored in memory?
Recursion uses more memory, because the recursive function adds to the stack
with each recursive call, and keeps the values there until the call is finished.
The recursive function uses LIFO (LAST IN FIRST OUT) Structure just like the
stack data structure. https://www.geeksforgeeks.org/stack-data-structure/
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is defined and the larger value
of a number can be solved by converting to a smaller one till the base case is
reached.
How a particular problem is solved using recursion?
The idea is to represent a problem in terms of one or more smaller problems,
and add one or more base conditions that stop the recursion. For example, we
compute factorial n if we know the factorial of (n-1). The base case for factorial
would be n = 0. We return 1 when n = 0.
Why Stack Overflow error occurs in recursion?
If the base case is not reached or not defined, then the stack overflow problem
may arise. Let us take an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7), and so on but the number
will never reach 100. So, the base case is not reached. If the memory is
exhausted by these functions on the stack, it will cause a stack overflow error.
What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A
function fun is called indirect recursive if it calls another function say fun_new
and fun_new calls fun directly or indirectly. The difference between direct and
indirect recursion has been illustrated in Table 1.
// An example of direct recursion
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
// An example of indirect recursion
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
What is the difference between tailed and non-tailed recursion?
A recursive function is tail recursive when a recursive call is the last thing
executed by the function. Please refer tail recursion article for details.
How memory is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on the
stack. A recursive function calls itself, the memory for a called function is
allocated on top of memory allocated to the calling function and a different copy
of local variables is created for each function call. When the base case is
reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
Let us take the example of how recursion works by taking a simple function.
// recursion
class GFG {
{
if (test < 1)
return;
else {
return;
// Driver Code
int test = 3;
printFun(test);
Output
3 2 1 1 2 3
Time Complexity: O(1)
Auxiliary Space: O(1)
When printFun(3) is called from main(), memory is allocated
to printFun(3) and a local variable test is initialized to 3 and statement 1 to 4
are pushed on the stack as shown in below diagram. It first prints ‘3’. In
statement 2, printFun(2) is called and memory is allocated to printFun(2) and
a local variable test is initialized to 2 and statement 1 to 4 are pushed into the
stack.
Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). prin
tFun(0) goes to if statement and it return to printFun(1). The remaining
statements of printFun(1) are executed and it returns to printFun(2) and so on.
In the output, values from 3 to 1 are printed and then 1 to 3 are printed. The
memory stack has been shown in below diagram.
Recursion VS Iteration
SR
Recursion Iteration
No.
Terminates when the base case becomes Terminates when the condition
1)
true. becomes false.
Every recursive call needs extra space in Every iteration does not require
3)
the stack memory. any extra space.
n if n == 0, n == 1;
fib(n) = fib(n-1) + fib(n-2) otherwise;
Recurrence Relation:
T(n) = T(n-1) + T(n-2) + O(1)
Recursive program:
Input: n = 5
Output:
Fibonacci series of 5 numbers is : 0 1 1 2 3
Implementation:
import java.util.*;
class GFG
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
// Driver Code
// Initialize variable n.
int n = 5;
System.out.print(fib(i)+" ");
Output
Fibonacci series of 5 numbers is: 0 1 1 2 3
Time Complexity: O(2n)
Auxiliary Space: O(n)
Here is the recursive tree for input 5 which shows a clear picture of how a big
problem can be solved into smaller ones.
fib(n) is a Fibonacci function. The time complexity of the given program can
depend on the function call.
fib(n) -> level CBT (UB) -> 2^n-1 nodes -> 2^n function call -> 2^n*O(1) -> T(n)
= O(2^n)
For Best Case.
T(n) = ?(2^n\2)
Working:
Problem 2: Write a program and recurrence relation to find the Factorial of n
where n>2 .
Mathematical Equation:
1 if n == 0 or n == 1;
f(n) = n*f(n-1) if n> 1;
Recurrence Relation:
T(n) = 1 for n = 0
T(n) = 1 + T(n-1) for n > 0
Recursive Program:
Input: n = 5
Output:
factorial of 5 is: 120
Implementation:
// Factorial function
// Stop condition
if (n == 0 || n == 1)
return 1;
// Recursive condition
else
// Driver code
int n = 5;
}.
Output
factorial of 5 is: 120
Time complexity: O(n)
Auxiliary Space: O(n)
Working:
Diagram of factorial Recursion function for user input 5.
import java.util.*;
class Main {
if (n == 0 || n == 1) {
return 1;
else {
}
}
Output
120
In this example, we define a function called factorial that takes an integer n as
input. The function uses recursion to compute the factorial of n (i.e., the product
of all positive integers up to n).
The factorial function first checks if n is 0 or 1, which are the base cases. If n is
0 or 1, the function returns 1, since 0! and 1! are both 1.
If n is greater than 1, the function enters the recursive case. It calls itself with n-
1 as the argument and multiplies the result by n. This computes n! by
recursively computing (n-1)!.
It’s important to note that recursion can be inefficient and lead to stack
overflows if not used carefully. Each function call adds a new frame to the call
stack, which can cause the stack to grow too large if the recursion is too deep.
In addition, recursion can make the code more difficult to understand and
debug, since it requires thinking about multiple levels of function calls.
However, recursion can also be a powerful tool for solving complex problems,
particularly those that involve breaking a problem down into smaller
subproblems. When used correctly, recursion can make the code more elegant
and easier to read.
What are the disadvantages of recursive programming over iterative
programming?
Note that both recursive and iterative programs have the same problem-solving
powers, i.e., every recursive program can be written iteratively and vice versa is
also true. The recursive program has greater space requirements than the
iterative program as all functions will remain in the stack until the base case is
reached. It also has greater time requirements because of function calls and
returns overhead.
Moreover, due to the smaller length of code, the codes are difficult to
understand and hence extra care has to be practiced while writing the code.
The computer may run out of memory if the recursive calls are not properly
checked.
What are the advantages of recursive programming over iterative
programming?
Recursion provides a clean and simple way to write code. Some problems are
inherently recursive like tree traversals, Tower of Hanoi, etc. For such
problems, it is preferred to write recursive code. We can write such codes also
iteratively with the help of a stack data structure. For example refer Inorder Tree
Traversal without Recursion, Iterative Tower of Hanoi.
What is Recursion?
The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called a recursive function. Using
recursive algorithm, certain problems can be solved quite easily. Examples of
such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree
Traversals, DFS of Graph, etc.
Types of Recursions:
Recursion are mainly of two types depending on whether a function calls
itself from within itself or more than one function call one another
mutually. The first one is called direct recursion and another one is
called indirect recursion. Thus, the two types of recursion are:
1. Direct Recursion: These can be further categorized into four types:
Tail Recursion: If a recursive function calling itself and that recursive call is
the last statement in the function then it’s known as Tail Recursion. After
that call the recursive function performs nothing. The function has to process
or perform any operation at the time of calling and it does nothing at
returning time.
Example:
// Recursion function
if (n > 0)
fun(n - 1);
// Driver Code
int x = 3;
fun(x);
}
} .
Output
3 2 1
Let’s understand the example by tracing tree of recursive function. That is
how the calls are made and how the outputs are produced.
import java.io.*;
class GFG
while (y > 0) {
y--;
// Driver code
int x = 3;
fun(x);
}
Output
3 2 1
Time Complexity: O(n)
Space Complexity: O(1)
Note: Time & Space Complexity is given for this specific example. It may vary
for another example.
So it was seen that in case of loop the Space Complexity is O(1) so it was
better to write code in loop instead of tail recursion in terms of Space
Complexity which is more efficient than tail recursion.
Why space complexity is less in case of loop ?
Before explaining this I am assuming that you are familiar with the knowledge
that’s how the data stored in main memory during execution of a program. In
brief,when the program executes,the main memory divided into three parts. One
part for code section, the second one is heap memory and another one is stack
memory. Remember that the program can directly access only the stack
memory, it can’t directly access the heap memory so we need the help of
pointer to access the heap memory.
Let’s now understand why space complexity is less in case of loop ?
In case of loop when function “(void fun(int y))” executes there only one
activation record created in stack memory(activation record created for only ‘y’
variable) so it takes only ‘one’ unit of memory inside stack so it’s space
complexity is O(1) but in case of recursive function every time it calls itself for
each call a separate activation record created in stack.So if there’s ‘n’ no of call
then it takes ‘n’ unit of memory inside stack so it’s space complexity is O(n).
Head Recursion: If a recursive function calling itself and that recursive call
is the first statement in the function then it’s known as Head
Recursion. There’s no statement, no operation before the call. The function
doesn’t have to process or perform any operation at the time of calling and
all operations are done at returning time.
Example:
import java.io.*;
class GFG{
// Recursive function
if (n > 0) {
fun(n - 1);
}
// Driver code
int x = 3;
fun(x);
Output
1 2 3
Let’s understand the example by tracing tree of recursive function. That is
how the calls are made and how the outputs are produced.
Time Complexity For Head Recursion: O(n)
Space Complexity For Head Recursion: O(n)
Note: Time & Space Complexity is given for this specific example. It may vary
for another example.
Note: Head recursion can’t easily convert into loop as Tail Recursion but it can.
Let’s convert the above code into the loop.
import java.util.*;
class GFG
{
// Recursive function
int i = 1;
while (i <= n) {
i++;
// Driver code
int x = 3;
fun(x);
}
// this code is contributed by shivanisinghss2110
Output
1 2 3
Tree Recursion: To understand Tree Recursion let’s first
understand Linear Recursion. If a recursive function calling itself for one
time then it’s known as Linear Recursion. Otherwise if a recursive function
calling itself for more than one time then it’s known as Tree Recursion.
Example:
Pseudo Code for linear recursion
fun(n)
{
// some code
if(n>0)
{
fun(n-1); // Calling itself only once
}
// some code
}
class GFG
// Recursive function
if (n > 0) {
// Calling once
fun(n - 1);
// Calling twice
fun(n - 1);
// Driver code
fun(3);
}
// This code is contributed by shivanisinghss2110
Output
3 2 1 1 2 1 1
Let’s understand the example by tracing tree of recursive function. That is
how the calls are made and how the outputs are produced.
import java.util.*;
class GFG {
if (n > 100)
return n - 10;
// Driver code
{
int r;
r = fun(95);
Output
91
Let’s understand the example by tracing tree of recursive function. That is
how the calls are made and how the outputs are produced.
2. Indirect Recursion: In this recursion, there may be more than one functions
and they are calling one another in a circular manner.
From the above diagram fun(A) is calling for fun(B), fun(B) is calling for fun(C)
and fun(C) is calling for fun(A) and thus it makes a cycle.
// Java program to show Indirect Recursion
import java.io.*;
class GFG{
if (n > 0) {
funB(n - 1);
if (n > 1) {
funA(n / 2);
}
// Driver code
funA(20);
Output
20 19 9 8 4 3 1
Let’s understand the example by tracing tree of recursive function. That is
how the calls are made and how the outputs are produced.