Queue•Medium
Double Ended Queue (Deque)
Double Ended Queue (Deque)

A Deque (pronounced 'deck') stands for Double-Ended Queue. It is a generalized linear data structure that permits element insertion and deletion at both the Front and Rear ends.
Types of Deques
-
Input-Restricted Deque:
- Insertion is allowed only at one end (usually the rear).
- Deletion is allowed at both ends (front and rear).
-
Output-Restricted Deque:
- Insertion is allowed at both ends (front and rear).
- Deletion is allowed only at one end (usually the front).
Modulo Circular Wrap Arithmetic
To avoid wasting array memory, a Deque is usually implemented circularly using modulo wrap logic:
-
Insert Front:
- Check if full:
((front == 0 && rear == MAX - 1) || front == rear + 1). - If empty: set
front = 0,rear = 0. - Wrap left: if
front == 0, setfront = MAX - 1. - Normal decrement:
front--. - Store:
arr[front] = value.
- Check if full:
-
Insert Rear:
- Check if full.
- If empty: set
front = 0,rear = 0. - Wrap right: if
rear == MAX - 1, setrear = 0. - Normal increment:
rear++. - Store:
arr[rear] = value.
-
Delete Front:
- Check if empty:
front == -1. - Extract:
value = arr[front]. - If 1 element left (
front == rear): reset pointers to-1. - Wrap right: if
front == MAX - 1, setfront = 0. - Normal increment:
front++.
- Check if empty:
-
Delete Rear:
- Check if empty.
- Extract:
value = arr[rear]. - If 1 element left: reset pointers to
-1. - Wrap left: if
rear == 0, setrear = MAX - 1. - Normal decrement:
rear--.