If you were creating a subarray (or array slice) implemented as a reference to the original array (plus bounds) it would be an O(1)
space overhead, irrespective of the size of the slice.
However, what you are creating (as temp
) is not a subarray. It is an independent array.
In this case your code will use O(k)
extra space for temp
. If k
is a constant (i.e. 2
) O(K)
is the same1 as O(1)
. But if k
is a scaling variable, then O(K)
is not reducible.
So ...
Does this violate the condition of O(1)
extra space?
Assuming k
is a scaling variable, yes.
(And if k
was a constant, and you did this a N
times where n
is a scaling variable, then you are allocating O(k * N)
or O(N)
extra space.)
Note that Java does not support array slices, but the List
API allows you to create sublists (with an O(1)
space overhead).
1 - From a mathematical perspective, O(1)
is an infinite set of functions. O(K)
where K
is a constant is the same infinite set of functions as O(1)
.