3

I am having a hard time getting the complexity of this for-loop

for (i = 4; i < n; i++)
{
    for (j = i - 3, sum = a[i - 4]; j <= i; j++)
    {
        sum += a[j];
    }
    System.out.println("sum thru" + i + ": " + sum);
}

I was thinking that the complexity of this nested loop is n^2 since it's a nested loop but someone told me that this is incorrect and nested loops aren't always a quadratic complexity!

I don't really know how to get the complexity in a good way. I've seen lots of articles about Big-O and complexity but they weren't helpful because they were expecting me to know everything, and they examples weren't the same as any of the examples I have.

I am not asking for the answer, I'm asking for the method. Is there any formula or method that will work for everything in this topic? I want to know how to get the number of assignments but unfortunately I have no clue how to do this.

Can someone explain it to me step by step?

2
  • It's not quadratic (with respect to n) because j always goes from i-3 to i. That means the inner loop always only has four iterations, a number independent of n. Commented Sep 20, 2013 at 1:50
  • Also, there is a formula: wolframalpha.com/input/… - it's just not the same formula for every algorithm. Commented Sep 20, 2013 at 1:50

2 Answers 2

10

You can see the outer loop iterates (n-4) times, since it is starting with 4 and condition is less than only. The inner loop will iterate maximum of 4 times. Because it starts with i-3 and ends in i. So the complexity is 4*(n-4). Hence the complexity is O(n).

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

4 Comments

Thanks for explaining. I got the inner lop part but I still didn't get why is the outer loop n-4? is it always going to be n-(the number of i) ?
Yes. The inner loop (not the block inside the inner loop) will get executed n-4 times, ie outer loop executes n-4 times.
@rullzrullz : It's because the outer loop starts at 4 and ends at n. So (n-4) times
Thank you very much for clarifying Ragavan and Panther
0

I don't think there is any formula that can solve all problems regarding to time complexity of algorithms. For me, the best way to figure out the big-O is going step by step, from the outer process to the inner process. I believe it is also the standard way for a beginner like you and me. For your question, first, the outer loop is O(n), which is straight forward. Then inside each loop, we have an inner process, which is another loop. That loop goes from i-3 to i, which is O(1). Then inside that process, it is a normal assignment statement, which is O(1) again. We take all together, the big-O will be O(n) * O(1) * O(1) = O(n)

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.