Delete from Beginning of Doubly Linked List in DSA Python - Time & Space Complexity
When we delete the first node from a doubly linked list, we want to know how the time needed changes as the list grows.
We ask: How much work does it take to remove the first item when the list is very long?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def delete_from_beginning(self):
if not self.head:
return # List is empty
self.head = self.head.next
if self.head:
self.head.prev = None
This code removes the first node from a doubly linked list by updating the head pointer and adjusting links.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Updating pointers of the first node and head reference.
- How many times: This happens only once per deletion, no loops or recursion involved.
Deleting the first node always takes the same steps, no matter how big the list is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2-3 pointer updates |
| 100 | 2-3 pointer updates |
| 1000 | 2-3 pointer updates |
Pattern observation: The number of steps stays the same no matter how large the list is.
Time Complexity: O(1)
This means deleting the first node takes a fixed amount of time regardless of list size.
[X] Wrong: "Deleting the first node takes longer if the list is bigger because we have to check all nodes."
[OK] Correct: We only change the head and its immediate neighbors, so the list size does not affect the steps needed.
Knowing that deleting from the start of a doubly linked list is quick helps you explain efficient list operations clearly in interviews.
"What if we changed this to delete from the end of the doubly linked list? How would the time complexity change?"