Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)
Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)
A Queue is a linear data structure governed by the FIFO (First In, First Out) principle: the first element added to the queue is the first one removed. Queues are indispensable for asynchronous task dispatching, printer spoolers, network packet routing, and Breadth-First Search (BFS) graph traversals.
1. Real-World Analogy: The Coffee Shop Counter
Think of ordering coffee at a drive-through or counter:
- The first customer to arrive in line is the first one served and leaves with their drink (FIFO).
- New customers join at the back (Rear / Enqueue).
- Customers leave from the front (Front / Dequeue).
- Cutting in line is forbidden!
2. Queue Operations & Mechanics
| Operation | Action | Time Complexity |
|---|---|---|
enqueue(val) | Appends an element to the rear of the queue | $O(1)$ |
dequeue() | Removes and returns the front element | $O(1)$ |
peek() / front() | Inspects the front element without removing it | $O(1)$ |
isEmpty() | Checks if the queue is empty | $O(1)$ |
3. Why Array .shift() is an Anti-Pattern in JavaScript/Python
In languages like JavaScript, calling arr.shift() to dequeue an element removes the first element and shifts every remaining element in memory 1 index to the left:
For 100,000 operations, using shift() takes seconds and triggers Time Limit Exceeded (TLE) in interviews.
The Solutions:
- 1Circular Array (Ring Buffer): Uses modulo arithmetic
(tail + 1) % capacityto wrap around without shifting. - 2Double-Ended Queue (Deque): Implemented via doubly linked nodes (Python
collections.deque).
4. Multi-Language Implementations: Circular Queue
Python 3 Implementation:
Modern JavaScript / TypeScript (High-Performance Deque via Doubly Linked Nodes):
5. Trace Table: Circular Queue of Capacity 3
| Operation | Action | Array State | head | tail | size | Return |
|---|---|---|---|---|---|---|
enQueue(10) | Writes at 0 | [10, _, _] | 0 | 1 | 1 | True |
enQueue(20) | Writes at 1 | [10, 20, _] | 0 | 2 | 2 | True |
enQueue(30) | Writes at 2 | [10, 20, 30] | 0 | 0 (wrapped!) | 3 (Full) | True |
enQueue(40) | Attempt write | [10, 20, 30] | 0 | 0 | 3 | False (Full) |
deQueue() | Removes 10 | [_, 20, 30] | 1 | 0 | 2 | True |
enQueue(40) | Writes at 0 | [40, 20, 30] | 1 | 1 | 3 | True (Reused 0!) |
Notice how index 0 was recycled seamlessly with zero element copies!
Multiple Choice Questions
array.shift() to implement a queue in performance-critical code an anti-pattern?Hash Tables: Hash Functions, Separate Chaining & Open Addressing
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.