Enqueue Operation in DSA Python - Time & Space Complexity
We want to understand how the time needed to add an item to a queue changes as the queue grows.
How does the enqueue operation's speed change when the queue gets bigger?
Analyze the time complexity of the following code snippet.
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
This code adds an item to the end of a queue represented by a list.
- Primary operation: Adding an item to the end of the list using append.
- How many times: Once per enqueue call, no loops involved.
Adding one item takes about the same time no matter how many items are already in the queue.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 append operation |
| 100 | 1 append operation |
| 1000 | 1 append operation |
Pattern observation: The time to add an item stays about the same even as the queue grows.
Time Complexity: O(1)
This means adding an item takes a constant amount of time regardless of queue size.
[X] Wrong: "Adding an item takes longer as the queue gets bigger because the list grows."
[OK] Correct: The append operation is designed to add at the end quickly, so it usually takes the same time no matter the size.
Knowing that enqueue is fast helps you design efficient queues and shows you understand how data structures work behind the scenes.
"What if we used a linked list instead of a list for the queue? How would the time complexity of enqueue change?"