Menu
Coddy logo textTech

Queue

Last updated

A queue has two live ends. New values join at the rear, and values leave from the front, so whatever waited longest is served first. That is FIFO, and it is exactly how a line at a counter behaves: joining at the back and being served from the front is what makes the wait fair. Press Play above and watch values enter on one side and leave from the other.

Because each end is tracked by its own index or pointer, both operations are O(1) and neither one shifts the rest of the data. That is why queues sit under anything that processes work in arrival order: print jobs, task and message queues, request buffers, and breadth-first search, which visits a graph level by level precisely because it keeps its frontier in a queue. Move the removal end to the back and you have a stack instead.

Time & space complexity

For a queue backed by a ring buffer or a linked list, the two standard implementations:

OperationComplexityNotes
EnqueueO(1)Write at the rear and advance the rear index.
DequeueO(1)Read at the front and advance the front index, with no shifting.
Peek (front)O(1)Read the front value without removing it.
SearchO(n)Not what a queue is for: you must drain it to look inside.
SpaceO(n)One slot per waiting value.

Step by step

StepWhat happens
1The queue starts empty, with front and rear pointing at the same slot.
2Enqueue writes the value at the rear, then advances the rear by one.
3Each further enqueue lands behind the values already waiting.
4Dequeue reads the value at the front, then advances the front by one.
5The value that comes back is always the one that has waited longest.
6When front meets rear the queue is empty again, and dequeueing further is an error.

Worked example

Enqueueing 3, 7, 5 and then draining the queue:

OperationQueue (front to rear)Returns
enqueue(3)[3]nothing
enqueue(7)[3, 7]nothing
enqueue(5)[3, 7, 5]nothing
dequeue()[7, 5]3, the oldest value
dequeue()[5]7
dequeue()[]5, the newest value, last

When to use a queue

Use it whenAvoid it when
Work must be handled in arrival order: job queues, request buffers, print spoolersYou need the most recent item first, which is a stack
You are exploring level by level, as breadth-first search doesItems must be served by priority rather than arrival, where a heap fits
A producer and a consumer run at different speeds and need a buffer between themYou need to search or index into the middle of the data
You want O(1) insertion and removal without shifting elementsYou would implement it by shifting an array on every dequeue, which makes it O(n)

Queue code

A clean, runnable Queue implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Queue code in Python

Python
1from collections import deque2
3queue = deque()4
5# Enqueue three values at the rear6for value in [3, 7, 5]:7    queue.append(value)8    print(f"enqueue {value} -> {list(queue)}")9
10# Dequeue them from the front: first in, first out11while queue:12    value = queue.popleft()13    print(f"dequeue {value} -> {list(queue)}")14
15print("empty:", len(queue) == 0)
Run this code in the Python Playground

Queue FAQ

What does FIFO mean?
First in, first out: the value that has waited longest is the next one served. A line at a ticket counter is the everyday picture. A stack is the opposite discipline, LIFO.
What is the difference between a queue and a stack?
Only which end you remove from. Both add at the rear in O(1); a queue removes from the front (FIFO), a stack removes from the same end it added to (LIFO). Their complexity tables are otherwise identical.
What are the main queue operations?
enqueue adds a value at the rear, dequeue removes and returns the front value, peek (or front) reads the front without removing it, and is_empty reports whether anything is waiting. All four are O(1).
Why is dequeue slow if I use a plain array?
Because removing index 0 from an array shifts every remaining element left, making each dequeue O(n). Real implementations avoid this with a ring buffer that advances a front index, or a linked list with a head pointer. Python's collections.deque and Java's ArrayDeque do this for you, while list.pop(0) does not.
What is a circular queue?
A queue in a fixed-size array where the front and rear indices wrap back to 0 when they run off the end. It reuses the slots freed by dequeues, so a queue of capacity n keeps working indefinitely instead of walking off the end of the array.
Where are queues used in real programs?
Task and message queues between services, print and job spoolers, request buffers in web servers, keyboard and event buffers, producer-consumer pipelines, and breadth-first search, where the queue is what makes the traversal go level by level.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED