In a singly linked list, the time taken to insert an element at an arbitrary…

2024

In a singly linked list, the time taken to insert an element at an arbitrary position — where the position is not known in advance and must be located by traversal — is:

  1. A.

    O(n)

  2. B.

    O(1)

  3. C.

    O(n log n)

  4. D.

    O(n2)

Attempted by 477 students.

Show answer & explanation

Correct answer: A

Concept

Inserting into a linked list has two parts: first locate the position where the new node must go, then splice it in by rewiring a fixed number of pointers. The splice is always constant time, so the overall cost is decided entirely by how the position is reached.

Applying it to a general insertion

  1. To insert at an arbitrary position, you start at the head and follow next-pointers until you reach the target spot. A linked list has no random access, so this traversal can visit up to all n nodes — that step is O(n).

  2. Once the predecessor node is reached, the actual link update (set the new node's next, then point the predecessor at the new node) touches a fixed number of pointers — O(1).

  3. Total general-case cost = O(n) traversal + O(1) splice = O(n). With no extra information about where to insert, O(n) is the cost we must report.

Cross-check against the other costs

  • O(1): true only for the special case where the insertion position is already known — inserting at the head, or when a pointer to the predecessor node is handed to you in advance. It counts the splice but ignores the lookup that the general case still requires.

  • O(n log n): this is the signature of comparison-based sorting / divide-and-conquer; a single insertion performs no sorting, so it does not arise here.

  • O(n^2): this would need a nested traversal (a loop inside a loop). A single insertion makes one pass at most, so quadratic cost is far too high.

Hence, in the general case the time to insert an element into a linked list is O(n).

Explore the full course: Cocubes Preparation