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.
Think of ordering coffee at a drive-through or counter:
| 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)$ |
.shift() is an Anti-Pattern in JavaScript/PythonIn 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.
(tail + 1) % capacity to wrap around without shifting.collections.deque).| 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!
array.shift() to implement a queue in performance-critical code an anti-pattern?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.