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.js
function render(values) {
return values.join(" -> ");
}
const queue = [];
for (const value of [10, 20, 30]) {
queue.push(value);
}
const removed = [];
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
- JavaScript represents this lesson's queue with a mutable
ArrayofNumbervalues.queue.push(value)appends10,20, and30at the back without replacing the array. - Dequeue uses
queue.shift(), which returns the front value and mutates the same array by moving later elements down one index. That preserves FIFO order for the replay, but it is O(n) per dequeue on a normal JavaScript array. - Removed values are collected in a second
Arraywithremoved.push(...). The replay showsqueuemoving from[]to[10, 20, 30], then to[20, 30]after removing10, and finally to[]withremoved = [10, 20, 30]. render(removed)usesvalues.join(" -> "), soconsole.logprints the deterministic output10 -> 20 -> 30. Allocation is limited to the short input literal for thefor...of, the queue array, the removed array, and the joined output string, all managed by the JavaScript runtime GC.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.