ProgrammingVery hardProduct company OA · code-tracing level

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 (i = 1; i * i <= n; i = i + 1)
    for (j = 1; j <= n; j = j * 2)
        Print "*"
    end for
end for
  1. A. O(n log n)
  2. B. O(√n)
  3. C. O(log² n)
  4. D. O(√n · log n)

Correct answer: D. O(√n · log n)

The outer loop runs while i² ≤ n, i.e. about √n times. The inner loop doubles j from 1 to n, about log₂ n + 1 times, independent of i. Total O(√n · log n). O(n log n) misreads the outer bound as i ≤ n; O(√n) ignores the inner loop.

More Pseudocode and Code Tracing questions

Exams that ask this topic