Queue
A queue is FIFO: the first item that enters is the first item that leaves.
Start with this mental model
A queue is FIFO: the first item that enters is the first item that leaves.
How it works, without unnecessary jargon
Values enter at the rear and leave from the front.
Queues are ideal when work must be processed in arrival order.
Read the algorithm as a sequence of decisions
Identify the invariant that must always remain true.
Follow the read/update path through the structure.
After a mutation, restore the invariant before returning.
enqueue A, B, C; dequeue returns A first.
class Queue {
#items = [];
#head = 0;
enqueue(value) { this.#items.push(value); }
dequeue() {
if (this.#head >= this.#items.length) return undefined;
return this.#items[this.#head++];
}
}Do not memorize the syntax. Follow the state that changes on each line and connect it to the invariant described above.
enqueue/dequeue O(1)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Good fit
- BFS
- Job scheduling
- Request buffering
What usually goes wrong
- Memorizing complexity without understanding representation.
- Ignoring worst-case shape or resizing/rebalancing costs.
A professional answer shape
Mention FIFO and explain that a production JS queue should avoid repeated Array.shift() for large workloads; use a head index or deque implementation.
What problem does Queue solve?
A queue is FIFO: the first item that enters is the first item that leaves.
What should I mention about complexity?
Its typical cost here is enqueue/dequeue O(1), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
What is the most common mistake?
Memorizing complexity without understanding representation.