0

Suppose I have a code with two for-loops:

int sum = 0;
for (int i = 1; i < N; i *= 2)
   for(int j = 0; j < i; j++)
      sum++;

How would I find the worst-case time complexity of this code? I've looked at many tutorials on finding time complexity and I understood them. But this one just seems a bit different from those in the tutorials.

TheSaviour
  • 61
  • 1
  • 7

2 Answers2

3

Lets do simple maths. Value of i in each iteration goes as 1,2,4,8... (log N + 1) terms. In each iteration, the inner loop goes i times. Adding up the values of i

T(N) = 1 + 2 + ... + (log N + 1) terms i.e. GP with a = 1 and r = 2 and n = (log N + 1)

T(N) = a[(rn-1)/(r-1)]
= 1[(2(logN+1) - 1)/(2-1)]
= 2N - 1
= O(N)

So the complexity is O(N) in all scenarios.

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
1

First consider a simpler case when N=2^k+1 for some integer k. In this case the outer loop has k iterations and the overall number of operations is

 T(N) = 1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1 = 2N - 3.

So the worst case complexity is at least O(2N - 3) = O(N).

Now suppose 2^k + 1 < N <= 2^(k+1) for some k. Then

 T(N) = 1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1 < 2N = O(N)

Therefore T(N) = O(N).

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76