what is the time complexity of this code? nlgn OR nlgn^2
for (int i = 1; i <= n ; i*=2 ) {
for (int j = 1; j <= n ; j*=2 ) {
for (int k = 0; k <= j ; k++) {
x++;
}}}
what is the time complexity of this code? nlgn OR nlgn^2
for (int i = 1; i <= n ; i*=2 ) {
for (int j = 1; j <= n ; j*=2 ) {
for (int k = 0; k <= j ; k++) {
x++;
}}}
First for takes log n time (exponential growth
)
Second for loop also takes log n time(exponential growth
)
Third one takes n time(linear growth
)
So overall time = multiply all ,We get
log n * log n * n
So time complexity is
O(n (logn)^2)
the time complexity for this will be n*((logn)^2) because the first loop will run for logn times the second will also run for logn times and the third loop will run for n times as it will be sum of gp 1+2+4+8. So the answer is n*(logn)*(logn)