VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 06: Stacks and queues

Lesson 6.1 of 10 in this module Unrolled Pro

Stacks, Queues and Monotonic Structures

Stacks and queues decide which part of the past you keep and in what order you get it back. From rescanning history (O(n²)), to a stack (last in, first out) and a queue (first in, first out) with their real Python costs, to monotonic stacks and deques that throw away every value that can never matter again, so each element is pushed and popped once: O(n). Then bounded buffers, the list.pop(0) trap, and how to pick the structure from the question.

about 10 min 4 Python examples 2 quick checks

The question this module answers: which part of the past do you still need? Many problems walk through a sequence and, at each step, ask something about what came before: the bracket that is still open, the most recent higher value, the oldest request still waiting, the largest value in the last k steps. Keeping all the past and rescanning it is O(n) per step. Keeping exactly the part that can still matter, in the right order, makes each step O(1) on average.

ML context. These structures sit under a lot of ML infrastructure:

  • Queues: request queues in model servers, data-loader prefetch buffers, breadth-first traversal of graphs.
  • Stacks: parsing and validating structured model output (JSON, tool calls), depth-first traversal, undo history.
  • Bounded deques: the last k losses for a rolling mean, a replay buffer of recent experience.
  • Monotonic structures: the rolling maximum of GPU memory or latency over a window (lesson 6.10), "how long until this metric was beaten".

1. The problem: rescanning the past

Task: for each position i, return the index of the previous greater element: the closest j < i with a[j] > a[i], or −1 if there is none.

The obvious approach walks backwards from each position:

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Stacks, Queues and Monotonic Structures"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee