Data Structures · Queue

Queue

Picture the line at a coffee shop. The first person to join is the first person served, and newcomers join at the back. Nobody sensible pushes to the front. A queue is that fairness rule as a data structure — you add at one end and remove from the other. It is how a computer serves requests in the order they arrived, so nothing waits forever.

What is it

A queue is a line. New items join at the back, and items leave from the front — the two ends do different jobs. This rule has a name: FIFO, first in, first out. Whatever has been waiting longest is served next, exactly like a fair line.

How it works

The queue remembers two spots: the front and the back. Adding an item, called enqueue, attaches it at the back and moves the back marker along. Removing an item, called dequeue, takes the one at the front and moves the front marker along. Because the two ends are tracked separately, adding and removing are each one quick step — nobody in the middle has to move. The order is preserved for free: whoever joined first reaches the front first.

Operations

Name Big-O Why
Enqueue (add to back) O(1) attach at the back, move the back marker
Dequeue (remove front) O(1) take the front item, move the front marker
Peek (look at front) O(1) read who's next without removing them
Is it empty? O(1) check whether the front has caught up to the back
Search inside O(n) finding a specific item means scanning the line

When to use

Use a queue whenever things must be handled in the order they arrived. Print jobs wait their turn. Tasks on a to-do list get done oldest-first. Messages between programs are delivered in order so none is skipped. Any time the fair answer is 'first come, first served,' a queue is the shape you want.

Watch out for

The catch is that you only reach the two ends — you cannot jump to someone in the middle of the line without walking there. A queue is the wrong tool when the newest item should go first; that is a stack. Watch out too for a naive array-backed queue: if you remove from the front by shifting everyone forward, each dequeue becomes slow. Real queues avoid this by tracking the front marker instead of moving anyone.

Analogy

A line at a coffee shop. You join at the back and get served from the front. The person who has waited longest goes next — fair, in order, no cutting.

Practice lessons

Lessons coming soon.