Skip to content
ReadMe Daily

Search articles, problems, patterns and every cheat sheet topic.

Data structures

Queue Visualiser

First in, first out. Join at the back, leave from the front.

Operations

A queue is first in, first out. Items join at the back and leave from the front, so the order is preserved.

Length
0
Operations run
0
class Queue {
items = [];
enqueue(value) {
this.items.push(value); // joins the back
}
dequeue() {
return this.items.shift(); // leaves the front
}
peek() {
return this.items[0];
}
}

The highlighted line is the one that produced the picture on the left.

What Queue does

A queue is a stack's opposite: items join at the back and leave from the front, so the order they arrived in is the order they are dealt with. That fairness is the point — it is why a queue, not a stack, is what makes breadth-first search find the shortest route.

How it works, step by step

  1. enqueue adds a value at the back, behind everything already waiting.
  2. dequeue removes and returns the value at the front, the one that has waited longest.
  3. peek reads the front without removing it.
  4. Everything behind the removed item shifts forward a place — which is why `shift()` is O(n), and why real queues keep a head index or use a linked list instead.

What to watch for

  • Values come out in exactly the order they went in, which is the whole difference from a stack.
  • Watch the shuffle on every dequeue. On a long queue that is real work, and it is the one performance trap in the naive implementation.
  • Give a stack and a queue the same operations on the hub's comparison view: same input, opposite output.

Cost

enqueueO(1)
dequeueO(n) with shift, O(1) with a head index
peekO(1)
SearchO(n)
Extra spaceO(n)

When to reach for it

Whenever order has to be preserved: job and message queues, request buffers, print spoolers, and breadth-first search. When both ends need to be fast, reach for a deque or a ring buffer rather than an array with shift.

Read more