Skip to main content

GATE CSE 2020Data Structures › Stacks, Queues, Linked Lists & ArraysVerified

GATE CSE 2020 PYQ: What is the worst case time complexity of inserting n n n elements into an empty linked list, if the linked…

What is the worst case time complexity of inserting nn elements into an empty linked list, if the linked list needs to be maintained in sorted order?

  1. A
    Θ(n)\Theta(n)
  2. B
    Θ(nlog⁡n)\Theta(n \log n)
  3. C
    Θ(n2)\Theta ( n^{2})
    Correct answer
  4. D
    Θ(1)\Theta(1)

Answer

(C) Θ ( n 2 ) \Theta ( n^{2}) Θ ( n 2 )

Approach

Model the process as performing one insertion at a time into a sorted linked list. Each new element must first be placed in its correct sorted position, which in the worst case requires scanning the entire current list. The total work is the sum of the costs of the individual insertions.

The standard worst-case analysis of insertion into a sorted linked list is that the ith insertion may scan i−1 nodes, giving total cost Θ(1+2+...+(n−1)) = $Θ(n^2)$. Although one can argue that if all n elements are available initially they could first be sorted in Θ(n log n) time, the usual exam interpretation of inserting n elements one by one into an initially empty sorted linked list gives $Θ(n^2)$. The official/community answer is C.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.