4
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.

0

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

Comments

4

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).

2 Comments

No. You can multiply by n, or get the summed inner loop complexity (better), but both means you're over counting. The answer should be O(2^n).
I think it should be O(2^n) as Teepeemm has explained.
0

Formally and methodically, you can use Sigma notation:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.