Queue

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

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

Implementation

1from collections import deque
2
3
4# time push: O(1)
5# 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)
6class Queue:
7
8    def __init__(self, arr=None):
9        self.arr = deque(arr) if arr is not None else deque()
10
11    def push(self, value):
12        self.arr.append(value)
13
14    def pop(self):
15        if len(self.arr) == 0:
16            raise IndexError("Queue is empty.")
17        return self.arr.popleft()
18        # list:pop(0) is O(n). collections.deque popleft() is O(1), could be used instead. This is an alternative - simply changing the pointer
19
20    def peek(self):
21        if len(self.arr) == 0:
22            raise IndexError("Queue is empty.")
23        return self.arr[0]
24
25    def __len__(self):
26        return len(self.arr)
27
28    def __str__(self):
29        return str(list(self.arr))
30
31    def __repr__(self):
32        return str(list(self.arr))
33
34    def is_empty(self):
35        return len(self.arr) == 0
36

Queue Operations

Empty QueueEnqueue elements to get started!