Last in, first out. Or not..
Match the removal rule to undo histories, work queues, and traversals.
01 Model the idea
A stack removes the newest item first; a queue removes the oldest. A Python list supports stack append/pop efficiently at the end. collections.deque supports efficient appends and removals at both ends, making it useful for queues. The access rule is part of the algorithm’s meaning: replacing a queue with a stack changes traversal order.
The removal rule defines the structure: latest first or earliest first.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
STACK: append and remove at the same end
QUEUE: append at the back and remove at the front03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
from collections import deque
history = []
history.append("type")
history.append("save")
print("undo:", history.pop())
queue = deque(["Build", "Test"])
queue.append("Review")
print("next:", queue.popleft())
print(list(queue))undo: save next: Build ['Test', 'Review']
- 1
The stack models the most recent action as the next action to undo. It retains older actions below it.
- 2
The queue processes arrivals in order. popleft avoids the repeated shifting cost of list.pop(0).
- 3
Check emptiness before removing, or handle IndexError when concurrent changes are possible. For coordinated multithreaded producer/consumer work, investigate queue.Queue rather than treating a deque as a complete coordination system.
04 Count the cost
Amortised O(1) list-end stack operations; O(1) deque-end operations
O(n) stored items
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use a deque to process three jobs in arrival order and collect their names.
Reveal one possible solution +
from collections import deque
jobs = deque(["A", "B", "C"])
finished = []
while jobs:
finished.append(jobs.popleft())
print(finished)06 Check your reasoning
Which operation removes the oldest queued element from deque?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.