1
for i = 1 to n   
  for j = 1 to i - 1

Is the runtime of this O(n^2)? Is there a good way to visualize things when approaching these types of problems to find the right answer?

2 Answers 2

3

Inner loop executes

1 + 2 + 3 + 4 + 5 +...n-1 = n*(n-1)/2 times

using formula for arithmetic progression sum, so overall compexity is O(n^2)

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

Comments

0

Each for loop is O(n), two for loops O(n)*O(n) = O(n^2)

Check this link out. The author explains good ways to approach figuring out runtimes.

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.