What should be the time complexity for below code block and why:
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
Outer loop: O(N)
Inner loop: Go on decreasing by the rate of i
,
Dry run: Suppose n=10 as
When i=0
, then j runs from j: 10 -> 1
, i.e. 10 times or n
times
When i=1
, then j runs from j: 10 -> 2
, i.e. 9 times or n-1
times
When i=2
, then j runs from j: 10 -> 3
, i.e. 8 times or n-2
times
--
When i=8
, then j runs from j: 10 -> 9
, i.e. 2
times
When i=9
, then j runs from j: 10 -> 10
, i.e. 1
times
So the inner loop comes out to be: n+ (n-1) + (n-2) . . . . (2) + (1)
So, it would be 1 + 2 + 3 ... (n-1) + (n)= n*(n+1)/2 = O(n*n)
Time Complexity: O(n*n*n)
Is this correct or not?