Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm Analysis, Time Complexity of algorithm

m=1;
for(i=1;i<=n;i++){
    m=m*2;
    for(j=1;j<=m;j++){
        do something that is O(1)
    }
}

What will be time complexity of the above code ?? Please tell me how to solve these types of problem.

like image 928
Ashok Naval Avatar asked Jan 13 '23 07:01

Ashok Naval


2 Answers

I prefer to look at these problems from the inside out. Removing the m, we have:

for(i=1;i<=n;i++){
    for(j=1;j<=2^i;j++){
        do something that is O(1)
    }
}

Or:

for(i=1;i<=n;i++){
    O(2^i)
}

So overall: sum_1^n O(2^i)=O(2^(n+1))=O(2^n).

like image 150
Teepeemm Avatar answered Jan 17 '23 15:01

Teepeemm


Inner loop will iterate 1 time, then 2 times, then ..., then 2^n times. So we have 1 + 2 + 4 + ... + 2^n = 2^(n + 1) - 1 = O(2^n) iterations of inner loop.

One iteration of inner loop has constant complexity, so summed_inner_loop_complexity = O(2^n).

Whole complexity is O(2^n).

like image 26
Ari Avatar answered Jan 17 '23 17:01

Ari