Enqueue values at the back and dequeue them from the front in first-in, first-out order.

Algorithm

Basic Implementation

basic.ts
function render(values: number[]) {
    return values.join(" -> ");
}
const queue: number[] = [];
for (const value of [10, 20, 30]) {
    queue.push(value);
}
const removed: number[] = [];
while (queue.length > 0) {
    removed.push(queue.shift());
}
console.log(render(removed));

The queue keeps the oldest value at the front and adds new values at the back.

Step 1 - Enqueue 10, 20, 30

New values join at the back. The oldest value, 10, stays at the front.

Queue after three enqueues: front 10, then 20, then back 30.nextnext10front2030back

Step 2 - Dequeue removes 10

Removing from the front returns 10 and makes 20 the new front.

After one dequeue: removed is 10; front moves to 20.next10removed20front30back

Complexity

  • Time: O(1) per operation with a real queue
  • Space: O(n)

Implementation notes

  • TypeScript declares both queue and removed as number[], and render(values: number[]) formats only numeric arrays.
  • Enqueue uses queue.push(value) for values 10, 20, and 30, mutating the same array from [] to [10, 20, 30].
  • Dequeue uses queue.shift() inside while (queue.length > 0), so the replay never observes an undefined dequeue. At runtime, shift removes the front value and reindexes the remaining array slots; TypeScript still types shift() as possibly undefined, so the checked source relies on the guard and runtime path rather than a non-null assertion.
  • Removed values are appended with removed.push(...). The trace shows queue becoming [20, 30] with removed = [10], then queue = [] with removed = [10, 20, 30].
  • console.log(render(removed)) prints 10 -> 20 -> 30. Visible allocation is the short input literal, the two arrays, and the joined output string; mutation is limited to push and shift operations.
front The front is the oldest value still waiting in the queue.
FIFO A queue removes values in first-in, first-out order.