0

Time complexity of a triple-nested loop

for(int i=0; i<n; i++)
    for(int j=i+1; j<n; j++)
        for(int k=j+1; k<n; k++)

I want to know the right solution of time complexity.

2
  • What have you tried so far? What do you think it is? Please demonstrate a basic effort to have solved the problem before posting it here. Commented Apr 2, 2014 at 19:48
  • Try to determine the number of iterations of the first loop, and for each iteration of the first loop, the number of iterations of the second one, and so on... Also, the overall complexity will depend on the complexity of the body of the third loop, but you can leave that for the end. You can try drawing a tree, it may be easier for you. Commented Apr 2, 2014 at 20:07

2 Answers 2

2

A formal solution to determine the order of growth of your algorithm:

enter image description here

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

Comments

1

First guess: three loops depending on n, so it should be O(n³)

If you try to compute the exact complexity you have to compute it for the inner an multiply it with the outer loop.

inner loop takes O(n-k)
middle loop takes O(n-j + n-j-1 + ... + n-j-n) = O((n-j) ⋅ (n-j+1) / 2) = O((n-j)²)
outer loop takes O((n-1)² + (n-2)² + ... + (n-n+1)²) = O(n³)

Sure this is not exact, but in terms of big-O it is exact enought.

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.