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

Correct answer: D. O(log² n)

The outer loop runs about log n times with i = n/2ᵏ. For that i, the inner loop doubles j from n/2ᵏ up to n, which takes k steps. Total 0 + 1 + … + log n ≈ (log n)²/2, i.e. O(log² n).

More Pseudocode and Code Tracing questions

Exams that ask this topic