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

Correct answer: A. O(n)

The inner loop runs i times and i halves each round: n + n/2 + n/4 + … < 2n. So the total work is linear, O(n). O(n log n) multiplies the log n rounds by the largest inner count n, which overestimates because the inner counts shrink geometrically.

More Pseudocode and Code Tracing questions

Exams that ask this topic