IAE Academy

GATE 2020 CS Q.6: solution and answer

GATE 2020 · CSQ.6 · 1 mark · MCQ

What is the worst case time complexity of inserting n² elements into an AVL-tree with n elements initially?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

See the question in the paper

Answer and solution

ANSWER

The worst-case time to insert n² elements into an AVL-tree initially holding n elements is Θ(n² log n) — option (C).

Official answer: CSource: Official answer key, GATE 2020 CS (IIT Delhi)

  1. A single insertion into an AVL tree of nodes costs in the worst case: to search down to the insertion point, plus rotations to rebalance (each rotation is ; checking balance factors back up the path is already counted in the search/traversal cost).

  2. We start with elements and insert more elements one at a time, so during this process the tree size ranges from (before the first new insertion) up to (after the last).

  3. For every value of in this range, : at the low end is trivially , and at the high end , since a constant multiple of is still .

  4. So every one of the insertions costs in the worst case, regardless of exactly where in the sequence it falls.

  5. Total worst-case time insertions per insertion .

  6. This matches option (C): .

KEY IDEA

Each AVL insertion costs Θ(log m) where m is the current tree size; since the tree size stays between n and n²+n throughout the process, log m is Θ(log n) for every single one of the n² insertions (because log(n²) = 2log n is still just a constant multiple of log n), so the n² insertions together cost Θ(n² log n) — not Θ(n² log(n²)), because Θ absorbs the constant factor of 2.

WATCH OUT FOR

Writing the final tree size as n²+n and concluding the last insertions cost Θ(log(n²)) = Θ(2 log n²) and then sloppily treating the exponent as if it must appear explicitly, sometimes leading to Θ(n² log n²) being (wrongly) simplified to Θ(n⁴) or left as a distinct-looking but numerically identical expression to n² log n — since Θ(log n²) = Θ(2 log n) = Θ(log n) exactly, both forms are the same complexity class, and no additional factor of n or n² should appear.

From the GATE 2020 CS paper. Every question of this paper · Download the full paper · All 26 Trees & heaps questions, with notes

More Trees & heaps questions