Skip to content
Official PYQ · 2020

GATE CS 2020 Q6 — Trees

Explain with AI

What is the worst case time complexity of inserting n2n^{2} elements into an AVL-tree with nn elements initially?

Choose one option
View worked solution

Answer: C

To find the worst-case time complexity of inserting n2n^2 elements into an AVL tree that initially contains nn elements, we analyze the cost of each individual insertion:

  1. AVL Tree Property: An AVL tree is a self-balancing binary search tree. The height of an AVL tree with kk elements is always Θ(log⁡k)\Theta(\log k).
  2. Cost of a Single Insertion: Inserting an element into an AVL tree of size kk takes time proportional to its height, which is Θ(log⁡k)\Theta(\log k).
  3. Total Cost of n2n^2 Insertions:

    As we insert n2n^2 elements one by one, the size of the tree grows from nn to n+n2n + n^2. Let ii be the index of the insertion (1≤i≤n21 \le i \le n^2). When inserting the ii-th element, the number of elements in the tree is n+i−1n + i - 1.

    The total time complexity T(n)T(n) is the sum of the insertion costs:

    T(n)=∑i=1n2Θ(log⁡(n+i))T(n) = \sum_{i=1}^{n^2} \Theta(\log(n + i))
  4. Asymptotic Analysis:

    For any ii in the range [1,n2][1, n^2], the size of the tree k=n+ik = n + i satisfies:

    n<n+i≤n2+nn < n + i \le n^2 + n

    Taking the logarithm on all sides:

    log⁡n<log⁡(n+i)≤log⁡(n2+n)<log⁡(2n2)=2log⁡n+1\log n < \log(n + i) \le \log(n^2 + n) < \log(2n^2) = 2\log n + 1

    Thus, for all ii, we have log⁡(n+i)=Θ(log⁡n)\log(n + i) = \Theta(\log n).

Substituting this back into the sum:

T(n)=∑i=1n2Θ(log⁡n)=n2⋅Θ(log⁡n)=Θ(n2log⁡n)T(n) = \sum_{i=1}^{n^2} \Theta(\log n) = n^2 \cdot \Theta(\log n) = \Theta(n^2 \log n)

Therefore, the worst-case time complexity is Θ(n2log⁡n)\Theta(n^2 \log n).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Trees questions