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

Correct answer: B. O(n log n)

For each i the while loop doubles j until it reaches i, about log₂ i steps. Summing log₂ i over i = 1…n gives log₂(n!) ≈ n log₂ n, so the complexity is O(n log n). O(n) treats the inner loop as constant time; O(n²) treats it as linear.

More Pseudocode and Code Tracing questions

Exams that ask this topic