4

Given an array a [1,2,3,4,5,6,7,8,9,10] let's say we have an algorithm that does the following:

for i in 0..a.length
  for j in 0..a.length
    ...

This would have a Big O runtime of O(n^2) because for each element it will traverse the entire array.

But what if the inner loop only traversed from the outer index forward?

for i in 0..a.length
  for j in i..a.length
    ...

That is, in comparison the first algo will look at n elements each iteration (outer loop). The second algo looks at:

  • n elements on the first iteration
  • n-1 elements on the second iteration
  • n-2 elements on the third iteration
  • ...
  • 1 element on the last iteration

When calculating Big O runtime for this kind of algo, is it still O(n^2)?

2 Answers 2

10

This is still O(n^2). The sum 1 + 2 + ... + n is n(n+1)/2, which is O(n^2).

More generally, for any polynomial function p(n), the sum of p(1) + p(2) + ... + p(n) is O(n p(n)). This proof is a lot harder, since you have to reason about sums of arbitrary powers of n, but it is indeed true. This means, for example, that if you nested a third loop inside out your inner loop that ranged from j to n, the runtime would be O(n^3).

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

Comments

0

If you are given that a is that specific array, then the time complexity for that algorithm is constant (or O(1)). Maybe I read what you asked too literally, but for the tightest bound to be O(n^2), a would have to be an array like [1,2,...,n]. If a is explicitly size 10, then, the algorithm always runs in the same number of steps.

Hopefully, this answer was unnecessary, but I'm a teaching assistant for a discrete math class, and we give trick questions pretty frequently that are very similar to this. If I misunderstood the question, then I apologize for wasting your time! Also, the answer that was already posted is very good!

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.