Sobes.tech
Junior

What is the asymptotic complexity of operations with list elements?

sobes.tech AI

Answer from AI

Depends on the type of list and operation.

Typically, the following list types are considered:

  • Singly linked list
  • Doubly linked list
  • Array (as a special case of list)

Operations:

  • Access by index
  • Insertion
  • Deletion
  • Search for value
Operation Singly linked list Doubly linked list Array
Access by index O(n) O(n) O(1)
Insertion O(1) (at beginning) O(1) (at beginning/end) O(n)
Deletion O(n) O(n) O(n)
Search for value O(n) O(n) O(n)

Explanations:

  • O(1) (Constant time): The operation takes a fixed amount of time regardless of list size. For example, accessing an element by index in an array.
  • O(n) (Linear time): The time to perform the operation is proportional to the list size. For example, searching for an element in an unsorted list.
  • O(log n) (Logarithmic time): The time increases logarithmically with the size of the list. Often seen when working with sorted data (e.g., binary search).

Details:

  • In a singly linked list: Insertion at the beginning is O(1). Insertion at the end or insertion/deletion by index requires traversal to the desired element, which is O(n).
  • In a doubly linked list: Insertion at the beginning and end is O(1). Insertion/deletion at a node's address is O(1), but searching for the node by value or index is O(n).
  • In an array: Access by index is O(1). Insertion or deletion in the middle of the array requires shifting elements, which is O(n). Insertion/deletion at the end, if there is capacity (e.g., in std::vector with reserved capacity), can be O(1) on average, but O(n) in the worst case (reallocation).