Card 09/ 09

RecapDifficulty: Intermediate2 min

Recap: Stacks and Queues

Newest first or oldest first, a deque for queues, and a ring buffer for a fixed size.

Stacks and Queues comes down to the seven ideas below, each listed with the card that covers it.

What the topic established, and which card it was on
The ideaWhere
A stack hands back the newest item and a queue the oldest, and neither reaches the middleStacks and Queues: Last In First Out, First In First Out
Write a stack from its top and a queue from its front, so the next item to leave comes firstTrace a Sequence of Stack and Queue Operations
"Most recent unfinished" is the cue for a stackStack Example: Matching Brackets in an Expression
"First come, first served" is the cue for a queue, and a stack can starve the earliest itemQueue Example: Serving Print Jobs in Arrival Order
A list, an ArrayDeque or a TypeScript array is the stack; a deque, an ArrayDeque or a head index is the queueStack and Queue in Python, Java and TypeScript
Removing from the front of an array moves every element behind it, so a queue of n becomes O(n²)Dequeuing From the Front of an Array
A ring buffer wraps head and tail with (index + 1) % capacity, and a count tells full from emptyRing Buffers: A Queue in a Fixed Array

The operations reduce to where each structure adds and removes, and what each costs when built on the storage that suits it; amortised means averaged over many pushes.

Where each structure adds and removes, and the cost of each operation
StructureAdds atRemoves fromCost of each operation
Stack on a dynamic arrayThe endThe endO(1), push O(1) amortised
Queue on a deque or a head indexThe backThe frontO(1)
Queue on a ring bufferThe tail slotThe head slotO(1), until it is full
Queue that removes at index 0 of an arrayThe backThe front, shifting the restDequeue O(n)

Together they let you choose the structure from the order a problem needs, trace it to its final state, and build it so that no operation moves an element it does not have to.