trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

confusing insertion and deletion time complexity on linked list

happyuniv opened this issue · comments

on linked-list page and doubly-linked-list page
time complexity on insertion is O(1) but on deletion is O(n)
Why is it different? shouldn't deletion be O(1) or insertion be O(n) ?

Insertion assumes appending to head/tail, so no traversal happens. Deletion means deleting a specific node, so you need to find it firstly.

@lazarljubenovic
Exactly, In case of Insertion: I guess we have both the pointers, the head and the tail, had it been just the head, We would need to traverse the whole list to insert at the end and complexity would have been O(n).
In case of deletion: as @lazarljubenovic mentioned we need to find the node first. thus, O(n).
Issue: #1001 must have been resolved now.