The space complexity concept is language agnostic.
And here, since you're creating a new structure on each iteration, you're adding as many space complexity.
If your algorithm is O(log n)
in time complexity, your space complexity for this part is also O(log n)
Also, do not forget that O
is the upper boundary an algorithm may reach. It is not the actual space the algorithm will use.
As noted correctly by @luk2302, if, instead of creating a new array each time, your algorithm makes it possible to reuse the existing one, then your space complexity drops to O(1)
You can confirm the assumptions made hereabove by running the following code snippets with the following VM options
-Xmx2048M -Xms64M -XX:+UseZGC
Constant Space Complexity
Here, the array is instantiated before the loop
Set<Long> set = new HashSet<>();
int[] a = new int[1_000_000];
while (true) {
long memory = Runtime.getRuntime().totalMemory();
set.add(memory);
Arrays.fill(a, Integer.MAX_VALUE);
System.out.println(set);
}
Prints
[67108864]
[67108864]
[67108864]
[67108864]
[67108864]
[67108864]
[67108864]
...
Linear Space Complexity
Set<Long> set = new HashSet<>();
while (true) {
long memory = Runtime.getRuntime().totalMemory();
set.add(memory);
int[] a = new int[1_000_000];
Arrays.fill(a, Integer.MAX_VALUE);
System.out.println(set);
}
Prints
[67108864]
[67108864, 100663296]
[67108864, 100663296, 134217728]
[67108864, 100663296, 134217728, 167772160]
[67108864, 100663296, 134217728, 167772160, 201326592]
[67108864, 100663296, 134217728, 167772160, 201326592, 234881024]
[67108864, 100663296, 134217728, 167772160, 201326592, 234881024, 268435456]
[67108864, 100663296, 134217728, 167772160, 201326592, 234881024, 268435456, 301989888]
[67108864, 100663296, 134217728, 167772160, 201326592, 234881024, 268435456, 301989888, 335544320]
[67108864, 100663296, 134217728, 167772160, 201326592, 234881024, 268435456, 301989888, 335544320, 369098752]
[167772160, 67108864, 100663296, 134217728, 201326592, 234881024, 268435456, 301989888, 335544320, 369098752, 402653184]