Data Structures & AlgorithmsModerateCodeforces Div2 B · complexity round

Problem: What is the time complexity of this loop in terms of n?

Problem: What is the time complexity of this loop in terms of n?
for i in range(1, n + 1):
    for j in range(i, n + 1, i):
        work()
  1. A. O(n^2)
  2. B. O(n sqrt n)
  3. C. O(n)
  4. D. O(n log n)

Correct answer: D. O(n log n)

The inner loop runs about n/i times, and summing n/i over i = 1..n gives the harmonic series n * H(n), which is O(n log n).

More Coding Interview Problems questions

Exams that ask this topic