Data Structures & AlgorithmsVery hardGATE CS · TCS NQT · Product Company SDE

What is the time complexity of this code, as a function of n?

What is the time complexity of this code, as a function of n?
for (int i = 0; i < n; i++)
  for (int j = i; j < n; j++)
    sum += a[i] * a[j];
  1. A. O(n)
  2. B. O(n log n)
  3. C. O(n^2)
  4. D. O(n^3)

Correct answer: C. O(n^2)

The inner loop runs n-i times; summed over i from 0 to n-1 this is n + (n-1) + ... + 1 = O(n^2), even though the inner loop shrinks.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic