Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of deletion in a linked list

I'm having a bit of trouble understanding why time complexity of link lists are O(1) according to this website. From what I understand if you want to delete an element surely you must traverse the list to find out where the element is located (if it even exists at all)? From what I understand shouldn't it be O(n) or am I missing something completely?

like image 241
Wolf Avatar asked Nov 29 '15 20:11

Wolf


People also ask

What is the time complexity of deletion?

In general, time complexity is O(h). Deletion: For deletion of element 1, we have to traverse all elements to find 1 (in order 3, 2, 1). Therefore, deletion in binary tree has worst case complexity of O(n). In general, time complexity is O(h).

Is LinkedList remove O 1?

Hello Ramakant ! The remove operation in LinkedList is O(1) only if you remove element which is at any of two ends of linked list. This is the best case and this is what LinkedList for - to add,remove elements sequentially.

What is the time complexity of linked list?

As Linked List elements are not contiguous, each element access incur a Time Complexity of O(√N).

What is the time complexity of insertion and deletion in singly linked list?

In a singly linked list, the time complexity for inserting and deleting an element from the list is O(n).


2 Answers

No, you are not missing something.

If you want to delete a specific element, the time complexity is O(n) (where n is the number of elements) because you have to find the element first.

If you want to delete an element at a specific index i, the time complexity is O(i) because you have to follow the links from the beginning.

The time complexity of insertion is only O(1) if you already have a reference to the node you want to insert after. The time complexity for removal is only O(1) for a doubly-linked list if you already have a reference to the node you want to remove. Removal for a singly-linked list is only O(1) if you already have references to the node you want to remove and the one before. All this is in contrast to an array-based list where insertions and removal are O(n) because you have to shift elements along.

The advantage of using a linked list rather than a list based on an array is that you can efficiently insert or remove elements while iterating over it. This means for example that filtering a linked list is more efficient than filtering a list based on an array.

like image 142
Paul Boddington Avatar answered Oct 21 '22 08:10

Paul Boddington


Your are correct.

Deletion:

1.If pointer is given in this case Time Complexity is O(1).

2.You DON'T have pointer to the node to be deleted(Search and Delete). In this case Time Complexity is O(n).

like image 45
Karthik Selvam Avatar answered Oct 21 '22 06:10

Karthik Selvam