Java – Do we include output space in space complexity

algorithm-analysisalgorithmsdata structuresjava

For example. I have a function which generates an array with random numbers.

int[] generateNum(int n) {
   int[] result = new int[n];
    /* Logic to generate random number */
    ...............
    return result;
}

Then space complexity of the above program should be O(n) or O(1)?

This question is more of about space complexity and very specific about whether to count data structure holding result in space complexity.

Best Answer

When a function or algorithm allocates n atomic items of memory like

   int[] result = new int[n];

then it has a space complexity of at least O(n), regardless of what this array is used for. If it is used exclusively for returning some results, or for a completely different purpose, does not matter.

However, many programming languages allow to return sequences of arbitrary numbers of items in ways the space complexity stays O(1), utilizing streams or generator expressions. For example, in C# you can write

IEnumerable<int> generateNum(int n) 
{
   for(int i=0;i<n;++i)
   {
       r= /* expression to generate random number */;
       yield return r; 
   }
}

Now it is up to the callers what they do with the result - if they process it sequentially, space complexity can stay O(1). If they store the full result in a list or an array, space complexity will be again O(n) at least.

(In Java, this seems to be possible, too, using Iterable<int>, but it seems to require more code).

Related Topic