Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a linked list faster than an array for insert and delete operations although it takes O(n) for both data structures?

The worst case running time of Insert and delete operations in an array is O(n), because we might need to make n shifts.

Same is the case for linked list too, if we want to insert or delete ith element we might need to traverse the whole list to reach the position where insert/delete is expected to be done. So Linked list also takes O(n) time.

So why is linked list preferred where insert/delete intensive operations are done.

like image 865
Krishna Sai Avatar asked Jul 17 '18 17:07

Krishna Sai


Video Answer


1 Answers

If you want to insert/delete the ith element in an array, searching only takes O(1) because of indexing. For example u can access the ith element of an array through array[i]. However, inserting/deleting that element, in the worst case, will take O(n) time. For example, if you inserted an element at position 0, you have to shift all the elements one spot to the right, which requires a traversal of the whole array.

If you want to insert/delete the ith element in an linked list, searching will take O(n) in the worst case because you have to keep a count and a pointer while traversing the list one element at a time. Once you arrive at the ith node, inserting/deleting only takes O(1) time since it's just a rearrangement of pointers, no shifting.

As to why linked lists are preferred when there are many inserts/deletions, I would say that one reason is that with linked lists you don't need to know how big it has to be ahead of time. Whereas with arrays, it may have to be resized often in anticipation of more/less elements.

like image 153
Chris Gong Avatar answered Sep 22 '22 10:09

Chris Gong