Data Structures & AlgorithmsVery hardProduct company OA

Which loop nests perform Θ(n log n) executions of work()?

Which loop nests perform Θ(n log n) executions of `work()`?
/* A */ for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work();
/* B */ for (i = 1; i <= n; i *= 2) for (j = 1; j <= i; j++) work();
/* C */ for (i = 1; i * i <= n; i++) for (j = 1; j <= n; j += i) work();
/* D */ for (i = n; i >= 1; i /= 2) for (j = 1; j <= n; j *= 2) work();
  1. A. A and D only
  2. B. B and C only
  3. C. A and C only
  4. D. A, B and C

Correct answer: C. A and C only

A: Σ n/i over i ≤ n = n·Hₙ = Θ(n log n), the harmonic sum. C: the same sum but only for i ≤ √n, giving n·H(√n) ≈ (n/2)·ln n – still Θ(n log n), since halving the log is only a constant factor. B: 1 + 2 + 4 + … ≤ 2n = Θ(n): the outer loop is logarithmic but the inner work is geometric. D: both loops are logarithmic, Θ(log² n). Treating B as 'log n iterations × up to n' (n log n) is the usual over-estimate.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic