Data Structures & AlgorithmsVery hardAmazon · Microsoft OA

What is the time complexity of this loop?

What is the time complexity of this loop?
i = n
while i > 0:
    for j in range(i):
        work()   # O(1)
    i //= 2
  1. A. Θ(n log n)
  2. B. Θ(log² n)
  3. C. Θ(n²)
  4. D. Θ(n)

Correct answer: D. Θ(n)

The inner loop runs n + n/2 + n/4 + … < 2n times in total, a geometric series, so the whole thing is Θ(n). Multiplying 'log n outer iterations × up to n inner' gives only an upper bound of n log n, which is not tight.

More Coding Interview Problems questions

Exams that ask this topic