A deque (double-ended queue) allows insertion and removal from either the front or the rear — it doesn’t follow the FIFO rule.
Types of Deque
- Input-restricted deque — input is restricted to a single end, but deletion is allowed at both ends.
- Output-restricted deque — output is restricted to a single end, but insertion is allowed at both ends.
Operations
In a circular array, once full, insertion wraps back to the beginning. In a linear array, once full, no more elements can be inserted — each operation below throws an “overflow” message in that case.
Setup: take an array (deque) of size n, with front = -1 and rear = 0.
Insert at the Front
- Check the position of
front. - If
front < 1, reinitializefront = n - 1(last index). - Otherwise, decrease
frontby 1. - Add the new key into
array[front].
Insert at the Rear
- Check if the array is full.
- If full, reinitialize
rear = 0. - Otherwise, increase
rearby 1. - Add the new key into
array[rear].
Delete from the Front
- Check if the deque is empty.
- If empty (
front == -1), deletion can’t be performed (underflow). - If there’s only one element (
front == rear), setfront = -1andrear = -1. - Else if
frontis at the end (front == n - 1), wrapfront = 0. - Otherwise,
front = front + 1.
Delete from the Rear
- Check if the deque is empty.
- If empty (
front == -1), deletion can’t be performed (underflow). - If there’s only one element (
front == rear), setfront = -1andrear = -1— otherwise follow the steps below. - If
rearis at the front (rear == 0), wraprear = n - 1. - Otherwise,
rear = rear - 1.
Check Empty
front == -1 means the deque is empty.
Check Full
front == 0 && rear == n - 1, or front == rear + 1, means the deque is full.
Time Complexity
All operations above run in constant time, O(1).