Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: A function does `for i in range(n): for j in range(i, n, i + 1): work()`. What is its time complexity?

  1. A. O(n²)
  2. B. O(n)
  3. C. O(n √n)
  4. D. O(n log n) – the inner loop runs about n/(i + 1) times, and Σ n/k is a harmonic sum

Correct answer: D. O(n log n) – the inner loop runs about n/(i + 1) times, and Σ n/k is a harmonic sum

For each i the inner loop steps by i + 1 from i to n: roughly n/(i + 1) iterations. Summing n/1 + n/2 + … + n/n = n·Hₙ ≈ n ln n. This is the same pattern as the sieve's inner loop. It is not quadratic because the step grows.

More Coding Interview Problems questions

Exams that ask this topic