The Wayback Machine - https://web.archive.org/web/20240723032313/https://www.geeksforgeeks.org/auxiliary-space-recursive-functions/
Open In App

Auxiliary Space with Recursive Functions

Last Updated : 13 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Prerequisite: Recursion
Memory used by a program is sometimes as important as running time, particularly in constrained environments such as mobile devices. 
For example if we need to create an array of size n, it will require O(n) space. If we need a two-dimensional array of size n x n , it will require O(n2). 
Stack space in recursive calls counts too as extra space required by a program. 
For example : 
 

C++




int sum(int n)
{
   if (n <= 0)
       return 0;
   return n + sum(n-1);
}


Java




static int sum(int n)
{
   if (n <= 0)
       return 0;
   return n + sum(n - 1);
}
 
// This code is contributed by Pratham76


Python3




def sum(n):
    if (n <= 0):
        return 0;
    return n + sum(n - 1);
 
 
# This code is contributed by Rajput-Ji


C#




static int sum(int n)
{
   if (n <= 0)
       return 0;
   return n + sum(n - 1);
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
function sum(n)
{
   if (n <= 0)
       return 0;
   return n + sum(n - 1);
}
 
</script>


In the above example function, each call adds a new level to the stack. 
 

     Sum(5)
->sum(4)
->sum(3)
->sum(2)
->sum(1)
->sum(0)

Each of these calls is added to the call stack and takes up actual memory. So code like this would take O(n) time and O(n) auxiliary space. 
However, just because you have n calls total doesn’t mean it takes O(n) space. Consider the below functions, which adds adjacent elements between 0 and n : 
Example: 
 

CPP




// A non-recursive code that makes n calls
// but takes O(1) extra space.
int pairSumSequence(int n)
{
    int sum = 0;
    for (int i=0; i<n; i++)
        sum += pairSum(i, i+1);
    return sum;
}
 
int pairSum(int a, int b)
{
    return a + b ;
}


Java




// A non-recursive code that makes n calls
// but takes O(1) extra space.
static int pairSumSequence(int n)
{
    int sum = 0;
    for (int i=0; i<n; i++)
        sum += pairSum(i, i+1);
    return sum;
}
 
static int pairSum(int a, int b)
{
    return a + b ;
}
 
// This code is contributed by Pushpesh Raj.


Python3




# A non-recursive code that makes n calls
# but takes O(1) extra space.
def pairSumSequence(n):
    sum = 0
    for i in range(n):
        sum += pairSum(i, i + 1)
    return sum
 
def pairSum(a, b):
    return a + b
     
# This code is contributed by Aman Kumar


C#




// A non-recursive code that makes n calls
// but takes O(1) extra space.
static int pairSumSequence(int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += pairSum(i, i+1);
    return sum;
}
  
static int pairSum(int a, int b)
{
    return a + b ;
}
  
// This code is contributed by Utkarsh


Javascript




// A non-recursive code that makes n calls
// but takes O(1) extra space.
function pairSumSequence(n) {
    let sum = 0;
    for (let i = 0; i < n; i++) // Iterate until n
        sum += pairSum(i, i + 1);
    return sum;
}
 
function pairSum(a, b) {
    return a + b;
}


In this example there will be roughly O(n) calls to pairSum. However, those calls do not exist simultaneously on the call stack, so we need only O(1) space. 
 



Similar Reads

What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Count Possible Decodings of a given Digit Sequence in O(N) time and Constant Auxiliary space
Given a digit sequence S, the task is to find the number of possible decodings of the given digit sequence where 1 represents 'A', 2 represents 'B' ... and so on up to 26, where 26 represents 'Z'. Examples: Input: S = "121" Output: 3 The possible decodings are "ABA", "AU", "LA" Input: S = "1234" Output: 3 The possible decodings are "ABCD", "LCD", "
6 min read
How to Optimize Auxiliary Space Of a DP Solution.
Space Optimization in Dynamic Programming Problems:This is a way to optimize the Auxlillary space of a solution which also produces the same correct result as before optimization. How to Optimize Space in the DP Solution:The idea is to store only the values that are necessary to generate the result for the current state of the DP solution. Avoid st
13 min read
Calculate ratio of area of a triangle inscribed in an Ellipse and the triangle formed by corresponding points on auxiliary circle
Given two integers A and B representing the lengths of semi-major and semi-minor axes of an ellipse, the task is to calculate the ratio of any triangle inscribed in the ellipse and that of the triangle formed by the corresponding points on its auxiliary circle. Examples: Input: A = 1, B = 2Output: 2Explanation: Ratio = B / A = 2 / 1 = 2 Input: A =
4 min read
Recursive Functions
A Recursive function can be defined as a routine that calls itself directly or indirectly. In other words, a recursive function is a function that solves a problem by solving smaller instances of the same problem. This technique is commonly used in programming to solve problems that can be broken down into simpler, similar subproblems. Need of Recu
4 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Recursive Linear Search Algorithm
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. How Linear Search Works? Linear search works by comparing each element of the data structure with the key to be found. To learn the
6 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Recursive program to print formula for GCD of n integers
Given a function gcd(a, b) to find GCD (Greatest Common Divisor) of two number. It is also known that GCD of three elements can be found by gcd(a, gcd(b, c)), similarly for four element it can find the GCD by gcd(a, gcd(b, gcd(c, d))). Given a positive integer n. The task is to print the formula to find the GCD of n integer using given gcd() functi
4 min read
Article Tags :
three90RightbarBannerImg