I recently did a technical interview and was asked for the memory complexity of the following algorithm that I wrote on the whiteboard. To be more specific, if I remember correctly, he was referring to "heap space":
public int[] fib = new int[1000];
public int fibonacci(int i) {
if (i == 0) return 0;
if (i == 1) return 1;
if (fib[i] != 0) return fib[i];
fib[i] = fibonacci(i - 1) + fibonacci(i - 2);
return fib[i];
}
Because he said "heap space", it sounds like he was giving me a clue that he wanted me to give the complexity of the following line of code:
public int[] fib = new int[1000];
I think I remember learning in school that new
in Java is like malloc
in C, where malloc
allocates storage off the heap. Assuming that my memory serves me correctly, let's now go back to my question: what is the memory complexity of this? Was I supposed to say O(1000)? O(n)? Something else?
Thanks!