0

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?

Raphael
  • 72,336
  • 29
  • 179
  • 389
  • "determine the Big Oh of the space complexity" Note that there's no such thing as "the Big O of some function", just as there's no such thing as "the integer bigger than $\pi$". – David Richerby Oct 05 '17 at 14:41
  • 2
    "Check my answer" questions are notoriously unsuited for this platform. Do you have a specific question? – Raphael Oct 05 '17 at 15:17
  • 1
    By the way, the space usage of code like this heavily depends on the language semantics and the compiler. I assume this is supposed to be sequential Java? Source code is usually offtopic here, but the salient characteristics are important. (Consider what would happen if arrays were a value type!) – Raphael Oct 05 '17 at 15:20
  • "The second block also needs to store only one integer for the return value. " -- how will you evaluate the sum? – Raphael Oct 05 '17 at 15:20

0 Answers0