Double-Ended Queues
Explore the concept of double-ended queues, or deques, which allow insertion and deletion at both the front and rear. Understand their JavaScript implementation and key operations, such as append, pop, and peek, all with constant time complexity. Learn how deques differ from stacks and queues, and discover their practical uses in algorithms like sliding window maximum and undo/redo functionality.
A deque stands for a double-ended queue. It is a more flexible version of a queue that allows insertion and deletion from both the front and the rear.
In a normal queue, insertion happens only at the rear and deletion happens only at the front. In a deque, both ends are fully active.
This makes the deque a generalization that can behave like a queue, a stack, or something in between, depending on how it is used.
A deque is useful when a problem needs controlled access to both ends of the structure. It appears in sliding window problems, palindrome checking, scheduling, and caching systems.
Example
To understand how a deque works, consider the following example. If a deque currently contains:
After inserting 88 at the front, the deque becomes:
After inserting 91 at the rear, the deque becomes:
After removing 88 from the front, the deque becomes:
After removing 91 from the rear, the deque becomes:
This two-sided behavior is what makes the deque more versatile than a regular queue.
JavaScript implementation
Below is the JavaScript implementation of the deque. Here's how to use it:
Explanation
To understand the above code, consider the following breakdown of how each function operates in the deque class:
Lines 7–9 (Inserting at the rear): The
append()method adds elements to the rear (right end) of the deque. Each call is an...