Queue

Enqueue and dequeue elements - watch FIFO ordering animate step by step.

Time O(1) · Space O(n)

Queue Operations

REAR (in)
flow
FRONT (out)
5
8
3
Size: 3

Implementation

Python
from collections import deque


# time push: O(1)
# time pop: O(1) (using collections.deque, because `list.pop(0)` is O(n). `arr = arr[1:]` is also O(n) creates a new array)
class Queue:

    def __init__(self, arr=None):
        self.arr = deque(arr) if arr is not None else deque()

    def push(self, value):
        self.arr.append(value)

    def pop(self):
        if len(self.arr) == 0:
            raise IndexError("Queue is empty.")
        return self.arr.popleft()
        # list:pop(0) is O(n). collections.deque popleft() is O(1), could be used instead. This is an alternative - simply changing the pointer

    def peek(self):
        if len(self.arr) == 0:
            raise IndexError("Queue is empty.")
        return self.arr[0]

    def __len__(self):
        return len(self.arr)

    def __str__(self):
        return str(list(self.arr))

    def __repr__(self):
        return str(list(self.arr))

    def is_empty(self):
        return len(self.arr) == 0
About Queue

How Queue Works

A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. The first element added is the first one removed. Queues model real-world scenarios like waiting lines and are essential in scheduling and breadth-first search algorithms.

Enqueue adds an element to the back of the queue. Dequeue removes and returns the element at the front. Both operations run in constant time with a proper implementation.

Complexity

Time
O(1)
Space
O(n)

When to Use Queue

  • Task scheduling and process management
  • Breadth-first search (BFS) in graphs
  • Print job management and request buffering