1
$\begingroup$

this code aims to determine whether there exists a contiguous subarray starting from index 0 in the given array A whose elements sum up to the target value S. can we apply Master theorem to find out its complexity

 public static boolean subsumFun(int[] A, int S, int i, int j) {
    if (i >= j)
        return S == 0;
    if (i + 1 == j)
        return A[i] == S || S == 0;

    int mid = (i + j) / 2;
    if (subsumFun(A, S, i, mid))
        return true;

    int s1 = 0;
    for (int k = i; k < mid; k++) {
        s1 += A[k];
    }

    return subsumFun(A, S - s1, mid, j);
}
$\endgroup$
1
  • 2
    $\begingroup$ Your question will be easier to recognise when you use a question mark. Proper capitalisation would make your post more pleasant to read. $\endgroup$ Commented Feb 11, 2024 at 8:04

1 Answer 1

1
$\begingroup$

Assume that the runtime $n$ is measured in the number of elements between i and j. In your method there are two recursive calls

    ...
    int mid = (i + j) / 2;
    if (subsumFun(A, S, i, mid))
        return true;
    ...

and

    ...
    return subsumFun(A, S - s1, mid, j);
}

which both halve the search space, so we have $a = 2$ recursive calls on a problem size of $\frac{n}{b} = \frac{n}{2}$. The work done in

    ...
    if (i >= j)
        return S == 0;
    if (i + 1 == j)
        return A[i] == S || S == 0;
    ...

can assumed to be constant, and the work done in

    ...
    int s1 = 0;
    for (int k = i; k < mid; k++) {
        s1 += A[k];
    }
    ...

is proportional to $\frac{n}{2}$. So the work outside of the recursive calls can be written as $$f(n) = c_1 \frac{n}{2} + c_2$$ for positive constants $c_1, c_2$.

The total runtime of your method can be expressed as the recurrence relation $T$ with

$$T(n) = aT(\frac{n}{b}) + f(n) = 2T(\frac{n}{2}) + c_1 \frac{n}{2} + c_2$$

therefore the Master theorem can be applied:

We have $f \in \Theta(n^{\log_2{2}}) = \Theta(n)$, so using the Master theorem we get $$T \in \Theta(n^{\log_2{2}} \cdot \log{n}) = \Theta(n \cdot \log{n}).$$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.