Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Stacks and queues
EXPERIMENT 10 / 66

Last in, first out. Or not..

Match the removal rule to undo histories, work queues, and traversals.

BY NAVAN SAMI◷ 8 MIN READSTARTERSTRUCTURE

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 THING THAT MUST STAY TRUE

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.

the_strategy.txt
STACK: append and remove at the same end
QUEUE: append at the back and remove at the front

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

stacks_and_queues.py
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))
↳ EXPECTED OUTPUT
undo: save
next: Build
['Test', 'Review']
  1. 1

    The stack models the most recent action as the next action to undo. It retains older actions below it.

  2. 2

    The queue processes arrivals in order. popleft avoids the repeated shifting cost of list.pop(0).

  3. 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

TIME

Amortised O(1) list-end stack operations; O(1) deque-end operations

SPACE

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

A SMALL MISSION

Use a deque to process three jobs in arrival order and collect their names.

Reveal one possible solution +
one_possible_solution.py
from collections import deque
jobs = deque(["A", "B", "C"])
finished = []
while jobs:
    finished.append(jobs.popleft())
print(finished)

06 Check your reasoning

QUICK SIGNAL CHECK

Which operation removes the oldest queued element from deque?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.