0
0
Data-structures-theoryHow-ToBeginner ยท 3 min read

Time Complexity of Queue Operations Explained Simply

The main queue operations enqueue (adding an item) and dequeue (removing an item) both have a time complexity of O(1) when implemented efficiently. Checking if the queue is empty or peeking at the front element also takes O(1) time, meaning these operations run very fast regardless of queue size.
๐Ÿ“

Syntax

A queue typically supports these operations:

  • enqueue(item): Add an item to the back of the queue.
  • dequeue(): Remove and return the front item.
  • peek(): View the front item without removing it.
  • isEmpty(): Check if the queue has no items.

Each operation is designed to run quickly, usually in constant time.

python
class Queue:
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.append(item)  # Add to back

    def dequeue(self):
        if not self.isEmpty():
            return self.items.pop(0)  # Remove from front
        return None

    def peek(self):
        if not self.isEmpty():
            return self.items[0]
        return None

    def isEmpty(self):
        return len(self.items) == 0
๐Ÿ’ป

Example

This example shows how enqueue and dequeue work and their time complexity implications when using a list-based queue.

python
queue = []

# Enqueue operations
queue.append('a')  # O(1)
queue.append('b')  # O(1)
queue.append('c')  # O(1)

print('Queue after enqueues:', queue)

# Dequeue operation
front = queue.pop(0)  # O(n) in Python list because it shifts elements
print('Dequeued:', front)
print('Queue after dequeue:', queue)

# Peek operation
if queue:
    print('Front item:', queue[0])  # O(1)

# Check if empty
print('Is queue empty?', len(queue) == 0)
Output
Queue after enqueues: ['a', 'b', 'c'] Dequeued: a Queue after dequeue: ['b', 'c'] Front item: b Is queue empty? False
โš ๏ธ

Common Pitfalls

Using a simple list and removing the front element with pop(0) causes O(n) time because all other elements shift left. This makes dequeue inefficient for large queues.

The better approach is to use a data structure like collections.deque in Python, which supports O(1) enqueue and dequeue operations from both ends.

python
from collections import deque

queue = deque()

# Efficient enqueue
queue.append('a')  # O(1)
queue.append('b')  # O(1)

# Efficient dequeue
front = queue.popleft()  # O(1)
print('Dequeued:', front)
print('Queue now:', list(queue))
Output
Dequeued: a Queue now: ['b']
๐Ÿ“Š

Quick Reference

OperationTime ComplexityNotes
enqueueO(1)Add item to back efficiently
dequeueO(1)Remove item from front efficiently with proper structure
peekO(1)View front item without removal
isEmptyO(1)Check if queue has no items
โœ…

Key Takeaways

Efficient queue operations like enqueue and dequeue run in constant time O(1).
Using a simple list with pop(0) for dequeue causes O(n) time due to shifting elements.
Use data structures like deque for true O(1) enqueue and dequeue.
Peek and isEmpty operations are always O(1) as they just check or view the front element.
Choosing the right queue implementation affects performance significantly.