ProgrammingHardTCS Digital · Infosys SP

What is the time complexity of the following pseudocode, as a function of n?

What is the time complexity of the following pseudocode, as a function of n?
for (each i from 1 to n)
    j = 1
    while (j < i)
        j = j * 2
    end while
end for
  1. A. O(n)
  2. B. O(n²)
  3. C. O(log n)
  4. D. O(n log n)

Correct answer: D. O(n log n)

For each i the while loop doubles j up to i, about log₂ i times. Σ log i for i = 1..n is log(n!) ≈ n log n, so the total is O(n log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic