What is a queue?
A queue is an ordered line of values where the oldest entry leaves first.
New items join at the back; the next item to serve comes from the front.
That rule is called FIFO — first in, first out.
- Front
- The end that leaves next — the person at the ticket window
- Back
- The end that accepts newcomers — the end of the line
- Enqueue
- Add a value at the back
- Dequeue
- Remove and return the value at the front
- FIFO
- First in, first out — the arrival order is the serve order
See it as a ticket line
Picture a counter with one window. People join at the back of the rope. The clerk always helps whoever is standing at the front — never someone in the middle.
Watch the line breathe. A new ticket joins at the back (enqueue). The person at the front steps up and leaves (dequeue). Arrival order is serve order.
Newcomers attach at the back. Only the front may leave.
Types of queues
Interview problems usually mean a simple FIFO queue. Variants change how you store the line, or whether both ends can accept work.
Circular queues reuse a fixed buffer by wrapping indices. Deques allow push and pop on both ends. Priority queues serve by rank, not arrival — that story lives with heaps.
Storage answers “how is it laid out?” Access answers “who leaves next?”
How it is stored in memory
A common layout is a fixed array used as a ring buffer. head points
at the front; tail points at the next free slot. When an index hits the end,
it wraps with modulo.
A linked queue keeps a front node and a back node instead — no wrap,
but each value pays for a pointer. Tap through the ring-buffer walk below.
Start with an empty buffer of capacity 4.
Operations
Think of the queue as a ticket line. Here are the everyday moves — tap Next on each demo to watch them happen. For copy-paste snippets and interview patterns, open the Functions tab.
Enqueue
Add someone at the back of the line. The front does not move.
Line is empty. Ana walks to the back — she is both front and back.
Dequeue
Serve the person at the front and remove them. Everyone else stays in order.
Three people waiting. Only the front may leave.
Peek front
Look at who is next without taking them out of line.
Look at whoever is first — do not remove them.
isEmpty
Ask whether anyone is still waiting before you dequeue.
Someone is waiting — the queue is not empty.
Level drain (BFS)
Breadth-first search keeps the next nodes to visit in a queue. Drain one level, enqueue the next — the line grows and shrinks as you walk the tree or graph.
BFS starts by enqueueing the root. Level 0 is in the queue.