-4

if there is given array, ex. arr

Java code:

int arr[] = {10,23,65,15,45};
int n = arr.length; //i.e n=5 
int k = 2;
int temp[] = new temp[k];

and if I create new array if size k which will be subarray of arr and will always have size less than original array arr.

Does this violate the condition of O(1) extra space?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    If you create a new array of size `k` then it take O(k) space. How could it not? – kaya3 Aug 12 '21 at 16:03
  • 1
    if k is a constant known at compile time, then it's still O(1), if it depends on n then it's not, in which case you probably need to operate on the orginal array directly without creating a new one. – assylias Aug 12 '21 at 16:14

1 Answers1

1

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216