data structurefree

Queue

A first-in, first-out collection: add at the back, remove from the front.

time
O(1)
space
O(n)

// step through it

step 1 / 7
1class Queue {2  items = [];3  head = 0;4  enqueue(x) {5    this.items.push(x);6  }7  dequeue() {8    return this.items[this.head++];9  }10}
head
= 0

empty

Start with an empty queue. head marks the front.

How it works

This queue keeps its items in an array and a head index that marks the front. Enqueue appends at the back; dequeue reads the item at head and moves head forward, so neither operation shifts the array. Queues power breadth-first search, task scheduling and buffering.