Delete Node at Beginning in DSA Python - Time & Space Complexity
When we delete a node at the beginning of a linked list, we want to know how the time it takes changes as the list grows.
We ask: Does deleting the first node take longer if the list is bigger?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def delete_at_beginning(self):
if self.head is not None:
self.head = self.head.next
This code removes the first node by moving the head pointer to the next node.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Updating the head pointer to the next node.
- How many times: This happens only once per deletion, no loops or repeated steps.
Deleting the first node always takes the same steps, no matter how big the list is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work stays the same even if the list grows larger.
Time Complexity: O(1)
This means deleting the first node takes the same amount of time no matter how big the list is.
[X] Wrong: "Deleting the first node takes longer if the list is very big because we have to check all nodes."
[OK] Correct: We only change the head pointer once; we do not look at other nodes, so size does not affect the time.
Understanding this simple operation helps build confidence in working with linked lists and shows you can reason about how changes affect performance.
"What if we changed the code to delete the last node instead? How would the time complexity change?"