Deque in Data Structure
A Deque (Double-Ended Queue) is a linear data structure that allows insertion and removal of elements from both the front and the rear ends, unlike a regular queue which only allows insertion at the rear and removal at the front.
Core Operations
addFront(item)— insert an element at the front.addRear(item)— insert an element at the rear.removeFront()— remove and return the front element.removeRear()— remove and return the rear element.isEmpty()/size()— utility operations.
from collections import deque
dq = deque()
dq.append(10) # addRear
dq.appendleft(5) # addFront
dq.pop() # removeRear -> 10
dq.popleft() # removeFront -> 5
Types of Deques
- Input-restricted deque: insertion allowed only at one end, deletion at both ends.
- Output-restricted deque: deletion allowed only at one end, insertion at both ends.
Complexity
| Operation | Time |
|---|---|
| Insert/Remove at front or rear | O(1) |
| Access by index | O(n) |
Applications
- Implementing both stacks and queues using a single structure.
- Sliding window problems (e.g., maximum in every window of size k).
- Undo operations that need access from both ends of a history list.
How a Deque Works Inside: The Circular Array Approach
A deque can be built on a doubly linked list, but many libraries use an array that wraps around at the ends. You keep an index for the front and a count of stored items. Moving the front backwards or the rear forwards uses the modulo operator, so the array behaves like a ring and no element ever has to shift.
class ArrayDeque:
def __init__(self, capacity):
self.buf = [None] * capacity
self.cap = capacity
self.front = 0
self.size = 0
def add_front(self, x):
if self.size == self.cap:
raise OverflowError("deque is full")
self.front = (self.front - 1) % self.cap
self.buf[self.front] = x
self.size += 1
def add_rear(self, x):
if self.size == self.cap:
raise OverflowError("deque is full")
rear = (self.front + self.size) % self.cap
self.buf[rear] = x
self.size += 1
def remove_front(self):
if self.size == 0:
raise IndexError("deque is empty")
x = self.buf[self.front]
self.front = (self.front + 1) % self.cap
self.size -= 1
return x
def remove_rear(self):
if self.size == 0:
raise IndexError("deque is empty")
rear = (self.front + self.size - 1) % self.cap
self.size -= 1
return self.buf[rear]
Walk through it with capacity 4: add_rear(1) stores 1 at index 0. add_front(0) moves the front to index 3, because (0 − 1) % 4 is 3. The deque now reads 0, 1 even though 0 sits physically at the end of the array.
The key idea is that the logical order (front to rear) is separate from the physical order in memory. The rear position is never stored; it is always calculated as front plus size, wrapped by the capacity. Keeping just two numbers makes the full and empty checks simple: the deque is empty when size is 0 and full when size equals the capacity. Real libraries grow the buffer instead of raising an error when it fills up, copying items into a larger array in logical order.
Worked Example: Maximum in Every Window
The sliding window maximum problem shows why removing from both ends matters. You store indices in the deque and keep their values in decreasing order. Old indices leave from the front; smaller values that can never be the maximum again leave from the rear.
from collections import deque
def window_max(nums, k):
dq, out = deque(), []
for i, x in enumerate(nums):
while dq and dq[0] <= i - k: # index fell out of the window
dq.popleft()
while dq and nums[dq[-1]] <= x: # smaller values are useless now
dq.pop()
dq.append(i)
if i >= k - 1:
out.append(nums[dq[0]])
return out
print(window_max([1, 3, -1, -3, 5, 3, 6, 7], 3)) # [3, 3, 5, 5, 6, 7]
Every index enters and leaves the deque at most once, so the whole scan runs in linear time instead of checking every window separately.
Deque, List or Plain Queue?
- Pick a deque when you add or remove at both ends, or when you need a fixed-size history.
- Pick a Python list when you mostly append, pop from the end and read by index.
- Pick queue.Queue when several threads share work, since it handles locking for you.
Python's deque also supports maxlen, which drops the oldest item automatically, and rotate(n), which shifts items around the ring.
recent = deque(maxlen=3)
for page in ["home", "cart", "pay", "done"]:
recent.append(page)
print(recent) # deque(['cart', 'pay', 'done'], maxlen=3)
Common mistakes
- Reading items in the middle of a large deque in a loop; that access is linear, not constant.
- Forgetting to test for emptiness before removing, which raises an error.
- Storing values instead of indices in window problems, which makes it impossible to tell when an item has expired.