What is the worst case time complexity of inserting \(n\) elements into an…

2020

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

  1. A.

    \(\theta (n)\)

  2. B.

    \(\theta (n \ log \ n)\)

  3. C.

    \(\theta (n^2)\)

  4. D.

    \(\theta (1)\)

Attempted by 765 students.

Show answer & explanation

Correct answer: C

Key idea: each insertion may require scanning the list to find the correct sorted position.

  • Worst-case time for the i-th insertion is O(i) because the list size is about i and you may need to traverse it.

  • Total worst-case time for n insertions is the sum O(1) + O(2) + ... + O(n) = Theta(n^2).

  • Therefore the worst-case time complexity of inserting n elements into an empty linked list while keeping it sorted is Theta(n^2).

Explore the full course: Gate Guidance By Sanchit Sir