Unit 6 of 8 · about 5 hours · implement
Stacks, queues, deques and monotone structures
Stacks suspend work until its context arrives; queues order it fairly. Their monotone variants turn quadratic scans into single passes across parsing, scheduling and windows.
You'll be able to
- Implement stack, queue, deque and circular buffer from the contracts with bounds.
- Derive the push/pop bound for monotone stacks and deques and state the maintained order.
- Diagnose empty-structure, order and expiry defects (values versus indices).
Covers
Read
In this order, only the parts listed
0 of 4 done
- Stacks and the call stack analogyDSA Handbook - Foundations and linear patterns
The LIFO contract; The call stack is the same data structure; LC 20 the deferred-match validator; What it actually costs (
pushamortized , LC 20 time and space) - Queues, deques, and circular buffersDSA Handbook - Foundations and linear patterns
The FIFO contract; The deque adds the back end; The circular buffer fixes the capacity; Why the patterns chapters teach the rest (LC 232 amortized queue); What it actually costs (
list.pop(0)againstdeque) - Monotonic stackDSA Handbook - Foundations and linear patterns
The pattern (pop-while-violating then push); Why the work stays linear ( aggregate); Worked example LC 739 on
[73, 74, 75, 71, 69, 72, 76, 73]; Largest rectangle: the sentinel-pop trick; Two pitfalls (indices, not values) - Monotonic dequeDSA Handbook - Foundations and linear patterns
The invariant (decreasing indices, front is the ); The pattern (drop-front, pop-tail, push, emit); Worked example LC 239 on
[1, 3, -1, -3, 5, 3, 6, 7]with ; What it actually costsThe cost table lists the max-heap with lazy deletion as beside space. The space column is right: stale entries stay buried, so the heap can hold entries and its worst case is .
Focus on
- Each index enters and leaves once: at most stack ops and at most deque ops. That is the whole linearity proof.
- Monotone structures store indices: values cannot report expiry.
- Deque order per slide: drop the expired front, pop smaller backs, push, emit the front.
- Python
listis the stack andcollections.dequeis the queue. Swapped roles cost per op at the wrong end.
Common mistakes · 3
- Storing values instead of indices: equal values from different positions become indistinguishable and expiry breaks.
- Emitting before pushing or popping the wrong end: the order is drop-front, pop-back, push, emit.
list.pop(0)as a queue (about 45x slower thandequeper drain at on the stated CPU and Python 3.13.14), and recursion past the default limit of 1000 frames, which raisesRecursionErrorinstead of growing.
Try it yourself
Closed-book, before checking anything
[1, 3, -1, -3, 5, 3, 6, 7] with output [3, 3, 5, 5, 6, 7]. Differential-test it against the brute force with Hypothesis (lengths up to 50, up to 10, derandomize, max_examples=200) in Python 3.13: expect 1 passed.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Prove the monotone stack is .Answer
Each element is pushed once and popped at most once, so the whole run performs at most stack operations (aggregate method).
2.Argue the two-stack queue is amortized .Answer
Each element moves from inbox to outbox at most once, so operations move at most elements.
3.Why must the deque hold indices?Answer
Expiry compares positions against . Values alone cannot tell a live equal from an expired one.
4.What does the heap alternative cost on sliding maximum, and when does the deque win?Answer
With lazy deletion, in the worst case: on increasing input no stale entry ever reaches the top, so the heap grows to entries. A heap or balanced tree with real deletion gets . The deque's beats both, and the gap grows with .
Practice
- LeetCode 20: Valid Parentheses
Implement the deferred-match validator with the terminal empty check. Judge with the Examples
(),()[]{}and([)].After submitting, compare against the handbook stacks section LC 20: the deferred-match validator.
- LeetCode 739: Daily Temperatures
Implement the pop-while-smaller template storing indices. Judge with the Examples
[73, 74, 75, 71, 69, 72, 76, 73]and[30, 40, 50, 60].After submitting, compare your trace against the handbook monotonic-stack worked example on the same input.
- LeetCode 239: Sliding Window Maximum
Attempt cold with hidden tags. Implement the monotone deque and judge with the Example
[1, 3, -1, -3, 5, 3, 6, 7], giving[3, 3, 5, 5, 6, 7].After submitting, read the AlgoMaster Sliding Window Maximum write-up (https://algomaster.io/learn/dsa/sliding-window-maximum) and the handbook monotonic-deque cost table.
You're done when
All three are accepted and your deque emits the worked trace exactly, with the argument written beside it.
Only when you can do this without notes.
Leads to
Notes
Resources · 1 for this unit, 7 more in the section
- DSA Handbook - Foundations and linear patternsHandbook Academy · primary
Study Part 0, Part 1, Part 3 and Part 4 in order, plus the Part 5 Linked-list fundamentals chapter. Use the routing-rule pages for arrays versus lists, map choice, stack versus queue, two pointers, sliding windows and prefix methods before seeing solved code.
Also in this section
- AlgoMaster DSA - linear structures sliceAlgoMaster · required
Attempt Design HashMap, Longest Substring Without Repeating Characters and Sliding Window Maximum cold. Hide tags, state the invariant first, and add randomized operation histories to Design HashMap.
- MIT 6.042J - asymptotics and invariantsMIT OpenCourseWare · support
Use the asymptotics, state-machine invariants and proof-method readings when a cost or correctness argument is weak. Solve only the matching problems.
- Algorithms lecture notes - amortized analysis and hashingJeff Erickson · support
Use note 9 Amortized Analysis for the summation, taxation, charging and potential-function proofs, and note 5 Hashing for chaining, universal hashing and open-addressing analysis, when the handbook treatment is too brief for a proof.
- Algorithmica - memory and data layoutSergey Slotin · support
Read the memory hierarchy, cache and complexity-model chapters, then measure one contiguous-versus-linked and one hash-versus-ordered workload crossover.
- NeetCode - unseen linear problemsNeetCode · optional
Use only for two tag-hidden transfer problems after the AlgoMaster slice. Do not start another full roadmap or watch a solution before the attempt is complete.
- Hypothesis documentation - Quickstart and stateful testingHypothesis · support
Follow Quickstart for
@givenstrategies and the pytest combination, Configuring test settings formax_examplesandderandomize, then Rule-based state machines (rule,precondition,invariant,run_state_machine_as_test) for randomized operation histories againstdictanddequeoracles. - CPython source - list and dict objectsPython Software Foundation · reference
Read
list_resizeinObjects/listobject.cfor the growth formula and pattern comment, and theUSABLE_FRACTIONdefinition, perturbation-probing comment and dummy-entry handling inObjects/dictobject.c. Read the cited functions and comments only.