For the algorithm below:
int x = 0;
for (int i = 0; i < n; i++)
for (j = 0; j < n; j++) {
if (j < i) j = j + n;
else x = x + 1;
}
So for this algorithm, my thought process goes like this:
The inner-loop performs n
iterations for j
when i=0
. However, for every value of i=0,1..n-1
, j
will only perform one iteration because the if-statement will evaluate to true and end the inner-loop.
Here is my source of confusion:
Since the outer-loop will perform n
iterations no matter what, and since the inner loop performs n
iterations when i=0
(very first iteration), how come the big-Oh time complexity isn't O(n²) and is instead, O(n) if the loops are nested and both perform n
iterations in the very first iteration?
As the nested loops always run to completion and there is a constant amount of code within the inner loop, the time complexity can be determined by taking the sum of the number of inner loop iterations in the worst case.
The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).
Putting all together. Continuing on the challenge to reduce the iterations on our algorithm, we have to perform the following steps: build the "index" with the information to be accessed later. iterate over the loop and fetch the additional information from the previously created "index"
The time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive calls in the recursive function, the Time Complexity is considered as O(Logn).
You have a line that says if (j < i) j = j + n;
which essentially breaks out of the loop (when j < i
), and since the inner loop starts at 0, this will trigger on the first iteration every time (except the first time), making it run in constant time.
You essentially only have one loop here. The code can be rewritten as
int x = 0;
for (int i = 0; i < n; i++) {
x = x + 1;
}
which makes it clear why it is O(n).
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