The Wayback Machine - https://web.archive.org/web/20241008143303/https://www.geeksforgeeks.org/why-is-tail-recursion-optimization-faster-than-normal-recursion/
Open In App

Why is Tail Recursion optimization faster than normal Recursion?

Last Updated : 10 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is tail recursion?

Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call.

What is non-tail recursion?

Non-tail or head recursion is defined as a recursive function in which the recursive call is the first statement that is executed by the function. It means there is no statement or operation before the recursive calls.

Why is tail recursion optimization faster than normal recursion?

In non-tail recursive functions, after one recursive call is over, there are more statements to compute, and hence all the functions do not unfold as soon as the base case is hit.

Every time when a recursive call is done (or any function call), a stack frame is added to the call stack. This keeps track of where you were at the time the function call was made so we can continue from where we left off. If this is done enough times, say through a recursive function to compute the 1 billionth Fibonacci number, you can get a stack overflow, which will typically terminate the process.

Tail recursion works off the realization that some recursive calls don’t need to “continue from where they left off” once the recursive call returns. Specifically, when the recursive call is the last statement that would be executed in the current context. Tail recursion is an optimization that doesn’t bother to push a stack frame onto the call stack in these cases, which allows your recursive calls to go very deep in the call stack.

If the last action of a method is a call to another method, instead of creating a new stack frame for the context of the new method (arguments, local variables, etc.), we can replace the current one. One of the drawbacks of normal recursive methods is that they heavily use the call stack. Tail-call optimization eliminates this problem and guarantees that the performance of a recursive algorithm is exactly as good as its iterative counterpart (yet potentially it is much more readable).

Example of tail recursive function:

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Tail recursion
void fun(int n)
{
  if(n == 0)
    return;
 
  cout<<n<<" ";
  fun(n-1);
}
 
// Driver Code
int main()
{
 
  fun(5);
 
  return 0;
}
 
// This code is contributed by Abhishek Thakur.


Java




// Java code to implement the approach
import java.util.*;
 
class GFG {
 
// Tail recursion
static void fun(int n)
{
    if(n == 0)
        return;
         
    System.out.print(n + " ");
    fun(n-1);
}
 
 
// Driver Code
public static void main (String[] args) {
 
    fun(5);
}
}
 
// This code is contributed by sanjoy_62.


Python3




# Tail recursion
def fun(n):
    if(n == 0):
        return
    print(n, end =" ")
    fun(n-1)
 
 
# Driver code
if __name__=="__main__":
      fun(5)


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
    // Tail recursion
    static void fun(int n)
    {
        if (n == 0)
            return;
 
        Console.Write(n + " ");
        fun(n - 1);
    }
 
    static public void Main()
    {
 
        // Code
        fun(5);
    }
}
 
// This code is contributed by lokesh.


Javascript




// JS code to implement the above approach
 
// Tail recursion
function fun(n)
{
  if(n == 0)
    return;
 
  console.log(n);
  fun(n-1);
}
 
// Driver Code
 
fun(5);
 
// This code is contributed by akashish__


Output

5 4 3 2 1 

Time Complexity: O(N)
Auxiliary Space: O(N)

Example of non-tail recursive function:

C++




#include <iostream>
using namespace std;
 
// Non-tail recursion
void fun(int n)
{
  if (n == 0)
    return;
 
  fun(n - 1);
 
  cout<<n<<" ";
}
 
int main() {
 
    fun(5);
    return 0;
}
 
// This code is contributed by akashish__


Java




// Java code to implement the approach
import java.util.*;
 
class GFG {
 
// Non-tail recursion
static void fun(int n)
{
    if(n == 0)
        return;
     
    fun(n-1);
     
    System.out.print(n + " ");
}
 
 
// Driver Code
public static void main (String[] args) {
 
    fun(5);
}
}
 
// This code is contributed by Pushpesh Raj.


Python3




# Non-tail recursion
def fun(n):
    if(n == 0):
        return
    fun(n-1)
    print(n, end =" ")
 
 
# Driver code   
if __name__=="__main__":
      fun(5)


C#




// C# code to implement the approach
using System;
 
public class GFG {
 
  // Non-tail recursion
  static void fun(int n)
  {
    if (n == 0)
      return;
 
    fun(n - 1);
 
    Console.Write(n + " ");
  }
 
  static public void Main()
  {
 
    // Code
    fun(5);
  }
}
 
// This code is contributed by lokesh.


Javascript




function fun(n) {
  if (n === 0) return;
 
  fun(n - 1);
 
  console.log(n);
}
 
fun(5);
// This code is contributed by akashish__


Output

1 2 3 4 5 

Time Complexity: O(N)
Auxiliary Space: O(N)

Related Articles:



Previous Article
Next Article

Similar Reads

Tail vs. Non-Tail Recursion
Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion. 1) Definition:Tail recursion is defined by having the recursive call as the last operation in the function before returningfunction factorial
3 min read
GFact | Why s.lower_bound(x) is faster than lower_bound(s.begin(), s.end(), x) in C++ STL?
Have you ever got TLE on solving a question using function lower_bound (s.begin(), s.end(), x) and when you use s.lower_bound(x) it runs just fine (here s is a Data structure and x is the value we are searching for) !! If "Yes" then why this happens? Well, we are going to find out this in the following article, but before that let's know about the
4 min read
Why is it faster to process sorted array than an unsorted array ?
Here is a C++ and java code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let's try out sample C++ and java programs to understand the problem statement better. Implementation: C/C++ Code // CPP program to demonstrate processing // time of sorted and unsorted array #include <iostream> #in
6 min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Prerequisite : Tail Call Elimination In QuickSort, partition function is in-place, but we need extra space for recursive function calls. A simple implementation of QuickSort makes two calls to itself and in worst case requires O(n) space on function call stack. The worst case happens when the selected pivot always divides the array such that one pa
12 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n < 0
8 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the function. Writing a tail recursion is little tric
4 min read
Tail Recursion in Python
Tail recursion is a special case of recursion where the recursive call is the last operation in the function. Therefore, the function returns the result of the recursive call directly, without performing any additional computation after the call. In some languages, tail-recursive functions can be transformed into iterative loops to avoid growing th
3 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which there are more greater (than a given number K) elements than elements less than or equal to K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray o
3 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
What is a Proper Tail Call?
What is a Proper Tail Call? Proper tail calls (PTC) is a programming language feature that enables memory-efficient recursive algorithms. Tail call optimization is where you can avoid allocating a new stack frame for a function because the calling function will simply return the value it gets from the called function. The most common use is tail-re
5 min read
Tail Call Optimisation in C
In C programming, Tail Call Optimization (TCO) is a technique that eliminates the need for an additional stack frame to store the data of another function by reusing the current function's stack frame. This optimization technique is only possible for tail function calls. What is Tail Call?The tail call is the type of function call where another fun
4 min read
Tail Call Elimination
We have discussed (in tail recursion) that a recursive function is tail recursive if the recursive call is the last thing executed by the function. C/C++ Code // An example of tail recursive function void print(int n) { if (n < 0) return; cout << " " << n; // The last executed statement is recursive call print(n-1); } Java
10 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Writing code faster in C++ STL
You are wondering some time coder write his code in 2 min or less how? No kidding! Although this tip may not be very useful for competitions such as ICPC or IOI. But there are recent ICPCs ranks where rank i and rank i + 1 are just separated by few minutes. When you can solve the same number of problems as your competitor, it is now down to coding
2 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Time taken by Loop unrolling vs Normal loop
We have discussed loop unrolling. The idea is to increase performance by grouping loop statements so that there are less number of loop control instruction and loop test instructions C/C++ Code // CPP program to compare normal loops and // loops with unrolling technique #include <iostream> #include <time.h> using namespace std; int main
6 min read
Find normal at a given point on the curve
Given a curve [ y = x(A - x) ], the task is to find normal at a given point ( x, y) on that curve, where A is an integer number and x, y also any integer. Examples: Input: A = 2, x = 2, y = 0 Output: 2y = x - 2 Since y = x(2 - x) y = 2x - x^2 differentiate it with respect to x dy/dx = 2 - 2x put x = 2, y = 0 in this equation dy/dx = 2 - 2* 2 = -2 e
6 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Find length of longest substring with at most K normal characters
Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P = "normal", Q = "00000000000000000000000000", K=1 O
12 min read
How to plot a normal distribution with Matplotlib in Python ?
Prerequisites: MatplotlibNumpyScipyStatistics Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ
2 min read