I'm trying to figure out Time function and Big O of a nested loop code,
public static int example5(int[ ] first, int[ ] second) { // assume equal-length arrays
int n = first.length, count = 0;
for (int i=0; i < n; i++) { // loop from 0 to n-1
int total = 0;
for (int j=0; j < n; j++) // loop from 0 to n-1
for (int k=0; k <= j; k++) // loop from 0 to j
total += first[k];
if (second[i] == total) count++;
}
return count;
}
According to my calculations the time function should lie in $n^4$, but the right answer is $n^3$.
Here are my solution steps,
- Constant operations = 2 times
- i-loop = 0 to n-1 = n times (although it's 2n+2, but I would pick the most higher order term)
- Constant operation = 1 time
- j-loop = 0 to n-1 = n x n times = $n^2$ times
- k-loop = 1+2+3+...+n-1+n = n x n x $n\frac{n+1}{2}$ times = $\frac{n^4 + n^3}{2}$ times
What I'm doing wrong, can someone please point out.