Queue
Imagine a line of people waiting to buy tickets. The person who joined the line first gets served first. Nobody cuts in front. Everyone waits their turn.
That's a queue. It follows one simple rule: First In, First Out — or FIFO for short.
Enqueue and Dequeue
There are two main moves:
- Enqueue — join the back of the line (add to the rear)
- Dequeue — serve the person at the front (remove from the front)
You can also peek — check who's at the front without serving them yet.
Where do queues appear?
Everywhere fair waiting is needed! Print jobs line up in a queue. Requests to a web server are queued. In algorithms, the famous BFS (Breadth-First Search) uses a queue to explore a graph level by level.
← → arrow keys to step · click elements to interact
Queue Operations
Why is enqueue and dequeue \(O(1)\)?
A queue tracks two pointers: the front and the back. Adding to the back takes one step. Removing from the front takes one step. No shifting needed. That's why both are instant. Under the hood, an efficient queue is often backed by a doubly linked list or a circular buffer.
Queues in BFS
In Breadth-First Search, you explore a graph in waves — all neighbors at distance 1 first, then distance 2, and so on. A queue makes this natural: enqueue neighbors you discover, dequeue the next node to explore. The order stays correct automatically.
Queue vs Stack
The key difference is order. A stack is LIFO — the newest item comes out first, like a pile of plates. A queue is FIFO — the oldest item comes out first, like a line of people. Both are useful depending on what order you need.
Complexity
BFS with a Queue
Quick check
Continue reading