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).