Stacks and Queues
Queue Enqueue/Dequeue
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));
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- TypeScript declares both
queueandremovedasnumber[], andrender(values: number[])formats only numeric arrays. - Enqueue uses
queue.push(value)for values10,20, and30, mutating the same array from[]to[10, 20, 30]. - Dequeue uses
queue.shift()insidewhile (queue.length > 0), so the replay never observes anundefineddequeue. At runtime,shiftremoves the front value and reindexes the remaining array slots; TypeScript still typesshift()as possiblyundefined, 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 showsqueuebecoming[20, 30]withremoved = [10], thenqueue = []withremoved = [10, 20, 30]. console.log(render(removed))prints10 -> 20 -> 30. Visible allocation is the short input literal, the two arrays, and the joined output string; mutation is limited topushandshiftoperations.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.