Queue
Очередь
A data structure that gives you items back in the order you added them. This rule is called first in, first out (FIFO).
What is a queue?
Think of a line at a checkout counter. New arrivals join the back, and the cashier serves whoever is at the front. A queue gives a program the same rule: the item that has been waiting the longest comes out next. That's first in, first out, or FIFO. It describes how callers use the queue, not how the items are laid out in memory.
Operations and implementations
- Enqueue: add an item at the back.
- Dequeue: remove and return the item at the front.
- Peek: look at the front item without removing it.
Check the API before peeking or removing: an empty queue may raise an exception or return a special result, depending on the implementation.
A linked-list queue keeps references to both ends. With a tail reference, adding an item doesn't require walking the list; removing the head is also O(1). An array-backed queue can avoid shifting elements by treating the array as a ring. The read and write positions wrap around when they reach the end, letting new items reuse slots freed by removals. In a fixed-capacity ring, adding and removing take O(1), but the queue needs a policy for when it's full. In a ring that doubles its capacity when full, an enqueue can take O(n) when it has to copy the items, while enqueue still costs O(1) amortized across a sequence of operations.
Example in Python
from collections import deque
pending = deque(['resize image', 'send email'])
print(pending.popleft()) # resize image
pending.append('generate report')
print(pending[0]) # send email (still queued)
A deque supports operations at both ends, but using only append and popleft gives it FIFO behavior. These operations take O(1). A list with append and pop(0) preserves the same order, but each front removal is O(n) because the remaining items shift left.
Where FIFO matters
Breadth-first search (BFS) puts discovered vertices in a queue until they're ready to be processed. Newly discovered neighbors go behind the vertices already waiting, so the search processes one distance layer before the next. A stack would take the most recently added item first instead. A priority queue follows a different rule too: the next item is chosen by priority, not simply by arrival order. Also, FIFO removal doesn't guarantee FIFO completion: if two workers take jobs from the same queue, the second job can finish first.
In interviews
A common exercise is to build a queue using two stacks. Push new items onto an input stack. To dequeue, pop from the output stack; if it's empty, first move everything from the input stack onto it. The transfer reverses the input order, putting the oldest item on top. Be ready to explain why one dequeue can take O(n), but each item is transferred at most once, giving O(1) amortized cost per operation.