ProgrammingHardTCS NQT · Accenture pattern

What is the time complexity of the following pseudocode, in terms of n, where the array has n elements?

What is the time complexity of the following pseudocode, in terms of n, where the array has n elements?
for (each i from 0 to n - 1)
    for (each j from 0 to n - 1)
        if (j > i)
            break
        end if
        Print arr[i], arr[j]
    end for
end for
  1. A. O(n)
  2. B. O(n log n)
  3. C. O(n^2)
  4. D. O(1)

Correct answer: C. O(n^2)

Even though the inner loop breaks early once j>i, it still always runs at least i+1 times (j from 0 to i), so the inner work is proportional to i on each outer pass; summing 1+2+...+n is still O(n^2).

More Pseudocode and Code Tracing questions

Exams that ask this topic