I recently had to do the assignment to determine the space complexity of methods similar to the following. I need to state the recurrence equation (line by line), derive the closed form and use that to determine the Big Oh of the space complexity. I have already handed it in, but I still have trouble understanding how to properly approach it.
public int call(int[] arr) {
return calculate(arr, 0, arr.length - 1);
}
private int calculate(int[] arr, int a, int b){
if(a > b) {
return 0;
}
System.out.println("a = " + a + "\t b = " + b);
return calculate(arr, a + 1, b)
+ calculate(arr, a, b - 1)
+ arr[a] + arr[b];
}
My line of thinking was the following:
If a > b then it needs a space to store the return value of 0, so the first block has a space complexity of 1. The second block also needs to store only one integer for the return value. However, it also calls upon itself twice. I reasoned that as the calls are consecutive, it can reuse the same space, so only needs the space of one.
This means that the recurrence equation is the following: \begin{align*} S(0)&=1\\ S(n)&=S(n-1) + 1 \end{align*}
The total number of simultaneous calls is most times it starts a new call without returning a value, which is at most $n$. Therefore the closed form equation is: \begin{align*} S(n)&=S(n-1) + 1\\ &=\big(S(n-2) + 1\big) + 1\\ &=S(0)+n\cdot 1\\ &=n+1 \end{align*} And therefore $S(n)=O(n)$.
Still, intuitively I feel that I'm doing something wrong. Can you please check if this is correct, or if not, tell me how to do it right?