0
for 1 to n
 for j=1 to 3
    for i=j to n
       count++

My answer: O(n^2)

Please correct me if I am wrong. Thank You

edit: The Innermost loop runs for O(n) as well as the Outermost loop. But what about j=1 to 3 ?

edit 2: From what I have learned, Space complexity can be calculated if there are -

  • Variable Declaration
  • Data Structures
  • Allocations
  • Function Call

But there are none of those in the above code. So what will be the space complexity ?

tuhi009
  • 29
  • 2
  • 9
  • Possible duplicate of [Big O for 3 nested loops](https://stackoverflow.com/questions/14510701/big-o-for-3-nested-loops) – Lasitha Petthawadu May 01 '18 at 09:52
  • 1
    You're correct as the 2nd line is a constant factor and doesn't affect the big-O complexity – silleknarf May 01 '18 at 09:56
  • 1
    thank you @silleknarf for the answer. – tuhi009 May 01 '18 at 10:03
  • 1
    Yes. You're right. The complexity is accurately (3*n*(n+1))/2 and in complexity world it's O(n^2). – AliJP May 01 '18 at 10:05
  • @AliJP It's actually `n(3n-2)` because the `j` in the third loop comes from the second loop, not the first one. – Holt May 01 '18 at 10:07
  • 1
    Hi, and welcome to s-o! It's not clear exactly what your question is: is it how to calculate complexity? Do you have specific question about the computation in this example? Just giving your answer (without working) and asking if it's correct doesn't make a good question because it's not clear what your specific problem is (other than presumably to hand in correct homework). – Paul Hankin May 01 '18 at 10:08
  • @PaulHankin yes. As i have said in the edited section, I don't know how to calculate the 2nd loop. – tuhi009 May 01 '18 at 11:33
  • I have added my thoughts on the space complexity. Can anyone help me there as well ? Thank you – tuhi009 May 02 '18 at 09:25

2 Answers2

1

It's O(n^2) because:

  • for 1 is O(n)
  • for 2 is O(1) - Final number of actions
  • for 3 is O(n) - i->n is still O(n) because the order depends on n

sum up - O(n^2).

Idan Str
  • 614
  • 1
  • 11
  • 33
1

Another way to approach this is to rewrite the code as follows:

for x= 1 to n
    for i = 1 to n
        count++
    for i = 2 to n
        count++
    for i = 3 to n    // considering 1 to 3 => [1, 3]
        count++

Then, we can argue that the time Complexity of all inner loops are O(n), i.e., O(n) + O(n) + O(n) = O(n).

The Time complexity of outer loop is also O(n) and for every iteration of outer loop we have O(n) iterations in the inner loop making it O(n^2).

Also, Space Complexity is O(1) as there are only a few variable declarations (the variables declared are: count, i, j; also you forgot to declare a variable in the outermost loop) that don't depend on any external parameter, i.e., the Space Complexity remains the same irrespective of the size of input.

Shubham
  • 2,847
  • 4
  • 24
  • 37