0

I was trying to find the time complexity of this nested loop

for (i = 1; i <= n; i++) {
  for (j = 1; j <= n; j++) {
    n--;
    x++;
  }
}

If there wasn't a n-- it would be n*n , O(n2) right?

But what if n reduces every time second loop runs?

What's the time complexity and big O of this nested loop?

If I consider n = 5, x equals 4, the second loop runs 4 time

2 Answers 2

4

The time complexity of the code is O(n). n is reduced by half for every iteration of the outer loop.

So we have n/2 + n/4 + n/8 + n/16 + ... + n/2^k = O(n)

where k is the number of iterations of the outer loop (basically i).

Note that the time complexity is independent of x.

If there wasn't a n-- it would be n*n , O(n2) right?

Yes

Sign up to request clarification or add additional context in comments.

9 Comments

What's the value of k?
@KellyBundy k is the number of iterations of the outer loop.
@danh Note that both j and n are moving towards each other, so by the time the loop condition j <= n is broken, they will have met in the middle.
But what is it? (Looking for an expression involving n)
@KellyBundy Good question. Not sure, I wasn't able to find an expression involving n even after plotting.
|
0

Another way to see it's O(n): You only enter the inner loop body if j <= n, and since j is positive, n must also be positive. But you decrease n every time, which you can only do O(n) times (where n is the starting value) and still have n positive.

Comments

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.