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();
- A. A and D only
- B. B and C only
- C. A and C only
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- A full binary tree (every node has 0 or 2 children) has 10 internal nodes. How many leaves does it have?
- An undirected graph with V vertices and E edges is stored as adjacency lists. How many entries do all the lists hold in total?
- Which traversal should be used to free every node of a binary tree, so that no node is freed before its children?
- Keys 40, 20, 60, 10, 30, 50, 70, 25 are inserted into an empty BST. Then 20 is deleted (a node with two children is replaced by its…
- A 3-ary (ternary) heap is stored in a 0-indexed array where node i has children 3i + 1, 3i + 2 and 3i + 3. What is the index of the parent…
- An undirected graph has edges A–B, A–C, B–D, C–D, C–E, D–F, E–G, F–G, G–H. How many vertices are at a shortest distance of EXACTLY 2 edges…