What would be the order of growth of the code below. My guess was, each loop's growth is linear but the if statement is confusing me. How do I include that with the whole thing. I would very much appreciate an explanatory answer so I can understand the process involved.
int count = 0;
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
for (int k = j+1; k < N; k++)
if(a[i] + a[j] + a[k] == 0)
count++;
There are two things that can be confusing when trying to determine the code's complexity.
The fact that not all loops start from 0. The second loop starts from i + 1
and the third from j + 1
. Does this affect the complexity? It does not. Let's consider only the first two loops. For i = 0
, the second runs N - 1
times, for i = 1
it runs N - 2
times, ..., for i = N - 1
it runs 0
times. Add all these up:
0 + 1 + ... + N - 1 = N(N - 1) / 2 = O(N^2).
So not starting from 0 does not affect the complexity (remember that big-oh ignores lower-order terms and constants). Therefore, even under this setting, the entire thing is O(N^3)
.
The if
statement. The if
statement is clearly irrelevant here, because it's only part of the last loop and contains no break
statement or other code that would affect the loops. It only affects the incrementation of a count, not the execution of any of the loops, so we can safely ignore it. Even if the count isn't incremented (an O(1)
operation), the if
condition is checked (also an O(1)
operation), so the same rough number of operations is performed with and without the if
.
Therefore, even with the if
statement, the algorithm is still O(N^3)
.
Order of growth of the code would be O(N^3).
In general k nested loops of length N contribute growth of O(N^k).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With