0

What would be the time complexity be of these lines of code?

Begin
 sum = 0
 For i = 1 to n do
 For j = i to n do
 sum = sum + 1
End

I want to say O(n) = 2n^2 + 1 but I'm unsure because of the i=j part.

John Kugelman
364k70 gold badges554 silver badges599 bronze badges
asked Nov 10, 2020 at 20:09
2
  • 1
    For O() you get rid of all non-leading polynomial terms (+1) and multiplicative constants (2*), so you're talking about O(n^2). Commented Nov 10, 2020 at 20:15
  • Note that 2n^2 + 1 = O(n) but not O(n) = 2n^2 + 1. Commented Nov 11, 2020 at 8:16

1 Answer 1

1

Your answer is correct!

A nested loop instinctively leads you to the right answer which is O(n^2). In doing Big-O analysis, it usually doesn't matter being specific to the point i.e. saying the time complexity is O(2n^2) or O(3n^2 + 1) -- saying O(n^2) is enough since that is the dominating task of the function.

The i = j condition simply makes it so that there are...

  1. i=1: n operations
  2. i=2: (n-1) operations
  3. ...
  4. i=n: 1 operation

So, the sum of all operations you do is 1 + 2 + ... n = n(n+1)/2 which is O(n^2).

answered Nov 10, 2020 at 20:21
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.