ProgrammingVery hardAmazon OA · Goldman Sachs OA

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

Correct answer: D. O(n)

The inner loop runs i times for i = 1, 2, 4, …, below n, and 1 + 2 + 4 + … + 2ᵏ < 2n. So the total work is O(n), not O(n log n) as the nested shape suggests.

More Pseudocode and Code Tracing questions

Exams that ask this topic