Junior — Middle
What is the time complexity of deleting an element in a singly linked list?
sobes.tech AI
Answer from AI
The time complexity of deleting an element in a singly linked list depends on whether we have a pointer to the element to be deleted or only to the head of the list.
- If we need to delete an element knowing only the head of the list, we first need to traverse the list to find the element and its previous node. This takes O(n) time, where n is the number of elements in the list.
- If we have a pointer to the previous element (or to the element itself if it is the first element), then deletion occurs in O(1) time, as it is enough to reconfigure the links.
Thus, in general, deleting an element in a singly linked list is an operation with a time complexity of O(n).