Data Structures & AlgorithmsHardAmazon · 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 = i
    while j <= n:
        work()     # O(1)
        j += i
  1. A. Θ(n²)
  2. B. Θ(n)
  3. C. Θ(n log n)
  4. D. Θ(n log log n)

Correct answer: C. Θ(n log n)

For each i the inner loop runs ⌊n/i⌋ times, and n/1 + n/2 + … + n/n = n·H(n) ≈ n ln n. This harmonic-sum pattern is how a sieve of divisors runs in O(n log n); the sieve of Eratosthenes, which loops only over primes, is O(n log log n).

More Coding Interview Problems questions

Exams that ask this topic