Deque
Дек
A double-ended queue lets you add or remove items at either end. It can behave like a regular queue or a stack, depending on which ends you use.
Also known as: двусторонняя очередь
What is a deque?
A deque (pronounced “deck”) is an ordered collection with two working ends. A regular queue takes new items at the back and removes them from the front. A deque also lets you insert at the front and remove from the back. Use opposite ends for insertion and removal and you get first-in, first-out (FIFO) behavior. Use the same end for both and you get last-in, first-out (LIFO) behavior, just like a stack.
How it works
The four core operations are push front, push back, pop front, and pop back. Most APIs also let you inspect the first or last item without removing it. Fast access to the middle is not part of the deque abstraction: Python's collections.deque takes O(n) time to index the middle, while C++ std::deque supports O(1) indexed access.
One way to build a deque is with a circular array. The positions marking the ends wrap around the array, so changing an end doesn't require shifting the other elements. If the array grows geometrically when full, an occasional resize costs O(n), but insertion is O(1) amortized. A doubly linked list with head and tail pointers is another option: operations at both ends take O(1), at the cost of extra links in each node.
Example: mix routine and urgent work
from collections import deque
pending = deque(["email", "report"])
pending.append("backup") # routine work goes to the back
pending.appendleft("alert") # urgent work goes to the front
print(pending.popleft()) # alert
print(pending.popleft()) # email
In Python, popleft() removes from the front without shifting the remaining items, unlike list.pop(0). Both pop() and popleft() raise IndexError on an empty deque. Putting urgent work at the front is a simple scheduling rule, not a general priority queue: two urgent items inserted at the front will be handled newest first.
Uses and interview questions
A bounded deque is handy for retaining recent events. With Python's deque(maxlen=100), appending on the right when the deque is full automatically discards the leftmost item. Breadth-first search uses a deque more simply: append newly discovered vertices at the back and take the next vertex from the front.
A classic interview problem is finding the maximum in each sliding window of width k. Store candidate indices in a deque in non-increasing order of their values. Drop expired indices from the front. Before appending a new index, drop smaller candidates from the back: the new value is larger and will stay in the window longer. The front then gives the current maximum. Although one step can remove several candidates, each index is inserted once and removed at most once, so the whole scan takes O(n) time and O(k) auxiliary space, excluding the output.