Imagine you have tasks arriving in order and you want to process them in the same order. Why is a queue better than a simple array for this?
Think about how tasks come in and how you want to handle them fairly.
Queues follow First-In-First-Out (FIFO) order, which matches the natural order of task arrival and processing. Arrays do not inherently enforce this order without extra code.
Consider a queue where we enqueue numbers 1, 2, 3, then dequeue twice, then enqueue 4. What is the state of the queue?
class Queue { private items: number[] = []; enqueue(item: number) { this.items.push(item); } dequeue() { return this.items.shift(); } print() { return this.items.join(' -> ') + ' -> null'; } } const q = new Queue(); q.enqueue(1); q.enqueue(2); q.enqueue(3); q.dequeue(); q.dequeue(); q.enqueue(4); console.log(q.print());
Remember dequeue removes from the front, enqueue adds to the back.
After enqueueing 1,2,3 the queue is 1->2->3->null. Dequeue twice removes 1 and 2, leaving 3. Enqueue 4 adds it to the end, so queue is 3->4->null.
Look at this TypeScript queue code. Why does calling dequeue on an empty queue cause an error?
class Queue { private items: number[] = []; enqueue(item: number) { this.items.push(item); } dequeue() { return this.items.shift(); } } const q = new Queue(); q.dequeue();
Think about which end of the array pop() removes from.
pop() removes the last element, so it does not follow FIFO order. Also, calling pop() on an empty array returns undefined, which may cause errors if not handled.
In BFS of a graph, why is a queue used to store nodes to visit next?
Think about how BFS explores nodes layer by layer.
Using a queue in BFS ensures nodes are processed in the order they are discovered, which corresponds to their distance from the start node, enabling level-wise traversal.
In real-time data streaming, why is a queue essential for handling incoming data packets?
Consider the importance of order and reliability in streaming data.
Queues act as buffers that hold data packets in arrival order, ensuring processing happens sequentially without loss or disorder, which is critical in streaming systems.
