Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the computational complexity of a nested loop

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?

like image 983
rullzing Avatar asked Feb 20 '26 15:02

rullzing


1 Answers

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

like image 90
Ragavan Avatar answered Feb 22 '26 04:02

Ragavan