Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of node deletion in singly- and doubly-linked lists

Tags:

Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?

like image 920
empty heart Avatar asked Dec 13 '09 06:12

empty heart


People also ask

What is the time complexity for deleting node in doubly linked list?

A. The time complexity is O(N) and space complexity is O(1), where N is the total node of the linked list.

What is the best case time complexity of deleting a node in singly linked list?

What is the best case time complexity of deleting a node in a Singly Linked list? Explanation: Deletion of the head node in the linked list is taken as the best case. The successor of the head node is changed to head and deletes the predecessor of the newly assigned head node. This process completes in O(1) time.

Why deletion is faster in doubly linked list?

In short: if you know the cell to remove in advance, the doubly-linked list lets you remove it in time O(1) while a singly-linked list would require time O(n). If you don't know the cell in advance, then it's O(n) in both cases. Hope this helps!


2 Answers

The problem assumes that the node to be deleted is known and a pointer to that node is available.

In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1).

Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n).

In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.

like image 125
Raj Avatar answered Sep 28 '22 09:09

Raj


Actually deletion in singly linked lists can also be implemented in O(1).

Given a singly linked list with the following state:

SinglyLinkedList:    Node 1 -> Node 2    Node 2 -> Node 3    Node 3 -> Node 4    Node 4 -> None     Head = Node 1 

We can implement delete Node 2 in such a way:

Node 2 Value <- Node 3 Value Node 2 -> Node 4 

Here we replace the value of Node 2 with the value of its next node (Node 3) and set its next value pointer to the next value pointer of Node 3 (Node 4), skipping over the now effectively "duplicate" Node 3. Thus no traversal needed.

like image 23
Ben Avatar answered Sep 28 '22 08:09

Ben