Data Structures & AlgorithmsVery hardAmazon · Microsoft OA

What is the time complexity of this loop?

What is the time complexity of this loop?
for i in range(1, n + 1):
    j = 1
    while j * j <= i:
        j += 1
  1. A. Θ(n log n)
  2. B. Θ(n²)
  3. C. Θ(n^1.5)
  4. D. Θ(n)

Correct answer: C. Θ(n^1.5)

For each i the inner loop runs about √i times, and Σ√i for i ≤ n ≈ (2/3)n^1.5. Recognising the √i bound (rather than log i or i) is the key.

More Coding Interview Problems questions

Exams that ask this topic