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.
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)
.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With