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

Stacks, queues, circular buffers and dequesMonotone stacks and deques
1

Read

In this order, only the parts listed

0 of 4 done

  1. 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 (push amortized , LC 20 time and space)

  2. 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) against deque )

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

  4. 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 costs

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

2

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 list is the stack and collections.deque is 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 than deque per drain at on the stated CPU and Python 3.13.14), and recursion past the default limit of 1000 frames, which raises RecursionError instead of growing.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement sliding-window maximum with a monotone deque: on [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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 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. 3.Why must the deque hold indices?Answer

    Expiry compares positions against . Values alone cannot tell a live equal from an expired one.

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

5

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 @given strategies and the pytest combination, Configuring test settings for max_examples and derandomize, then Rule-based state machines (rule, precondition, invariant, run_state_machine_as_test) for randomized operation histories against dict and deque oracles.

  • CPython source - list and dict objectsPython Software Foundation · reference

    Read list_resize in Objects/listobject.c for the growth formula and pattern comment, and the USABLE_FRACTION definition, perturbation-probing comment and dummy-entry handling in Objects/dictobject.c. Read the cited functions and comments only.