Data Structures & AlgorithmsHardProduct-company MCQ pattern

What is the time complexity of this code fragment?

What is the time complexity of this code fragment?
for (int i = 1; i <= n; i++)
    for (int j = i; j <= n; j += i)
        work();   // O(1)
  1. A. O(n √n)
  2. B. O(n log n)
  3. C. O(n)
  4. D. O(n²)

Correct answer: B. O(n log n)

For each i the inner loop runs about n/i times, so the total is n(1 + 1/2 + … + 1/n) = n·Hₙ ≈ n ln n = O(n log n). The step j += i is what stops it being O(n²).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic