Stacks, Queues & Monotonic Stacks
- Implement a stack, a queue and a ring-buffer deque idiomatically in Go (with generics) and know their costs
- Recognize problems that are secretly about nesting (stack), arrival order (queue) or "next greater/smaller" (monotonic stack)
- Write monotonic stack and monotonic deque solutions and prove their O(n) bound
- Explain where ring buffers appear in real systems (Go channels, io_uring, exchange pipelines, flight recorders)
TL;DR
- Stack (LIFO) = Go slice:
appendto push,s[:len(s)-1]to pop. Use it for nesting (brackets, undo, compensations), iterative DFS, and expression evaluation. - Queue (FIFO) = slice with a moving head for short-lived BFS; a ring buffer for long-lived queues; buffered channels only for goroutine hand-off.
- Monotonic stack: keep elements in increasing or decreasing order; when a new element breaks the order, pop — the newcomer is the next greater/smaller of everything popped. Each element is pushed and popped once → O(n).
- Monotonic deque: the same idea for a moving window — front holds the current max/min, stale indexes leave from the front. Sliding window maximum in O(n).
- Ring buffer: fixed array + head/tail indexes wrapping modulo capacity (a bit mask when capacity is a power of two). Bounded memory, no allocation per operation.
- Store indexes, not values, on monotonic stacks: you usually need distances or window bounds.
When to reach for it
- Matching or nesting: brackets, tags, function calls, "decode
3[a2[c]]" → stack. - "Most recent unmatched thing" or "undo the last step" → stack. In a saga, compensations run in reverse order of completed steps — a stack (Distributed Transactions: 2PC, TCC, Saga).
- Process in arrival order, level by level, shortest path in an unweighted graph → queue (BFS, see Graphs).
- "Next greater / previous smaller element", "how many days until…", "span", "largest rectangle", "visible people" → monotonic stack.
- "Max/min of every window of size k" → monotonic deque.
- "Keep the last N events in fixed memory" → ring buffer.
Core concepts
Stack
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := len(s.items) - 1
v := s.items[last]
s.items[last] = zero // do not retain pointers in the unused tail
s.items = s.items[:last]
return v, true
}
func (s *Stack[T]) Peek() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
func (s *Stack[T]) Len() int { return len(s.items) }
In interviews, an inline []int with stack = stack[:len(stack)-1] is fine and faster to write; the generic type is what you would put in a codebase.
Queues and deques
Options in Go, in order of preference by situation:
- Slice with a head index (or
q = q[1:]) for BFS that runs once and is discarded. The popped prefix is not reused, but it is released whenappendreallocates; fine for bounded work. - Ring-buffer deque for long-lived queues (worker backlogs, sliding windows): O(1) at both ends, amortized O(1) growth, no per-element allocation.
container/listwhen you need O(1) removal from the middle given a handle (LRU caches). Each element is a separate allocation, and values areany.- Buffered channel for passing work between goroutines. It is a locked ring buffer internally, but it blocks when full or empty and you cannot peek, so it is a poor general-purpose data structure (Goroutines & Channels).
A growable ring-buffer deque — capacity stays a power of two, so wrapping is & (cap − 1):
// Deque is a growable ring buffer.
type Deque[T any] struct {
buf []T
head int // index of the front element
n int // number of elements
}
func (d *Deque[T]) Len() int { return d.n }
func (d *Deque[T]) mask() int { return len(d.buf) - 1 }
func (d *Deque[T]) grow() {
nb := make([]T, max(8, 2*len(d.buf)))
for i := range d.n {
nb[i] = d.buf[(d.head+i)&d.mask()]
}
d.buf, d.head = nb, 0
}
func (d *Deque[T]) PushBack(v T) {
if d.n == len(d.buf) {
d.grow()
}
d.buf[(d.head+d.n)&d.mask()] = v
d.n++
}
func (d *Deque[T]) PushFront(v T) {
if d.n == len(d.buf) {
d.grow()
}
d.head = (d.head - 1) & d.mask()
d.buf[d.head] = v
d.n++
}
func (d *Deque[T]) PopFront() (T, bool) {
var zero T
if d.n == 0 {
return zero, false
}
v := d.buf[d.head]
d.buf[d.head] = zero
d.head = (d.head + 1) & d.mask()
d.n--
return v, true
}
func (d *Deque[T]) PopBack() (T, bool) {
var zero T
if d.n == 0 {
return zero, false
}
i := (d.head + d.n - 1) & d.mask()
v := d.buf[i]
d.buf[i] = zero
d.n--
return v, true
}
// Front and Back panic on an empty deque; check Len first.
func (d *Deque[T]) Front() T { return d.buf[d.head] }
func (d *Deque[T]) Back() T { return d.buf[(d.head+d.n-1)&d.mask()] }
Ring buffers in real systems
A fixed-capacity ring buffer never allocates after construction, which makes latency predictable — the reason it shows up wherever tail latency matters:
- Go buffered channels keep elements in a circular buffer with send/receive indexes inside the runtime's channel struct.
- Linux io_uring shares submission and completion rings between user space and the kernel (I/O Models: Blocking, epoll, io_uring).
- LMAX Disruptor, a pre-allocated ring with sequence counters, was built for a retail FX exchange's matching pipeline (Stock Exchange).
- Flight recorders and debug buffers: keep the last N log lines, traces or transactions per account and dump them when something goes wrong.
Overwrite-oldest variant for "last N events":
// Ring keeps the most recent len(buf) values, overwriting the oldest.
type Ring[T any] struct {
buf []T
next int
full bool
}
func NewRing[T any](size int) *Ring[T] { return &Ring[T]{buf: make([]T, size)} }
func (r *Ring[T]) Add(v T) {
r.buf[r.next] = v
r.next = (r.next + 1) % len(r.buf)
if r.next == 0 {
r.full = true
}
}
// Snapshot returns the stored values, oldest first.
func (r *Ring[T]) Snapshot() []T {
if !r.full {
return slices.Clone(r.buf[:r.next])
}
return append(slices.Clone(r.buf[r.next:]), r.buf[:r.next]...)
}
Design choice to state explicitly: when the buffer is full, do you overwrite (telemetry, debug logs) or reject/block (payment instructions — dropping one is a correctness bug, so apply backpressure instead).
Monotonic stack
Keep a stack whose values are monotone (say, non-increasing from bottom to top). When a new value x arrives, pop every element smaller than x: x is the next greater element for each of them. Then push x. Every index is pushed once and popped at most once, so the whole scan is O(n) despite the inner loop.
Choosing the direction:
| Question | Stack order (bottom → top) | Pop while |
|---|---|---|
| Next greater element | non-increasing | top < x |
| Next smaller element | non-decreasing | top > x |
| Previous greater element | non-increasing | top ≤ x, then the top (if any) is the answer |
| Previous smaller element | non-decreasing | top ≥ x, then the top (if any) is the answer |
Strict vs non-strict comparison decides how ties are handled — think about duplicates explicitly (Largest Rectangle and "sum of subarray minimums" double-count if you get it wrong).
Monotonic deque
For a sliding window maximum, keep a deque of indexes whose values are decreasing from front to back. On each new index: drop the front if it left the window; drop from the back every index with a value ≤ the new value (it can never be a maximum again while the newer, larger value is in the window); push the new index. The front is always the window maximum.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Slice stack | Fastest, contiguous, trivial | Growth spikes if unbounded | Almost always for LIFO |
Slice queue (q = q[1:]) | One-liner | Prefix memory reclaimed only on reallocation | One-shot BFS |
| Ring-buffer deque | O(1) both ends, no per-op allocation | More code; growth copies | Long-lived queues, sliding windows |
| Fixed ring (overwrite) | Bounded memory, predictable latency | Loses old data by design | Telemetry, last-N history |
container/list | O(1) middle removal with a handle | Allocation per element, any values, poor locality | LRU/LFU internals |
| Buffered channel | Goroutine-safe hand-off, backpressure | No peek, blocking semantics, lock cost | Producer/consumer between goroutines |
| Monotonic stack/deque | O(n) next-greater and window extremes | Subtle tie handling | Range-extreme and span problems |
In practice
Problem 1 — Valid Parentheses (LeetCode 20)
Problem. Given a string of ()[]{} characters, decide whether every bracket is closed in the correct order.
Approach. Push openers; on a closer, the top must be its matching opener. The string is valid only if the stack ends empty.
func isValid(s string) bool {
pairs := map[byte]byte{')': '(', ']': '[', '}': '{'}
stack := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
switch c {
case '(', '[', '{':
stack = append(stack, c)
default:
open, ok := pairs[c]
if !ok || len(stack) == 0 || stack[len(stack)-1] != open {
return false
}
stack = stack[:len(stack)-1]
}
}
return len(stack) == 0
}
Complexity. O(n) time, O(n) space. Quick win: an odd-length string can be rejected immediately.
Problem 2 — Daily Temperatures (LeetCode 739)
Problem. For each day, how many days until a warmer temperature (0 if none)?
Approach. Next-greater-element with a monotonic stack of indexes. When day i is warmer than the day on top, day i resolves it.
Trace for [73, 74, 75, 71, 69, 72, 76, 73]: 74 resolves 73 (1 day); 75 resolves 74; 71 and 69 stack up under 75; 72 resolves 69 (1) and 71 (2); 76 resolves 72 (1) and 75 (4); 73 waits forever.
func dailyTemperatures(temps []int) []int {
ans := make([]int, len(temps))
var stack []int // indexes; temperatures non-increasing bottom to top
for i, t := range temps {
for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
j := stack[len(stack)-1]
stack = stack[:len(stack)-1]
ans[j] = i - j
}
stack = append(stack, i)
}
return ans
}
Complexity. O(n) time (each index pushed and popped once), O(n) space.
Problem 3 — Sliding Window Maximum (LeetCode 239)
Problem. Return the maximum of every contiguous window of size k.
Approach. Monotonic deque of indexes (values strictly decreasing front to back), using the Deque above. The heap alternative is O(n log k) and needs lazy deletion of stale entries.
func maxSlidingWindow(nums []int, k int) []int {
var dq Deque[int]
out := make([]int, 0, max(0, len(nums)-k+1))
for i, v := range nums {
if dq.Len() > 0 && dq.Front() <= i-k {
dq.PopFront() // front index left the window
}
for dq.Len() > 0 && nums[dq.Back()] <= v {
dq.PopBack() // can never be a maximum while v is in the window
}
dq.PushBack(i)
if i >= k-1 {
out = append(out, nums[dq.Front()])
}
}
return out
}
Complexity. O(n) time, O(k) space. Real-world reading: "peak transactions-per-second over every rolling 60-second window" on a payment gateway dashboard.
Problem 4 — Largest Rectangle in Histogram (LeetCode 84)
Problem. Bars of width 1 with given heights; find the area of the largest rectangle that fits under the skyline.
Approach. For each bar, the widest rectangle of exactly its height extends to the first lower bar on each side. Keep a stack of indexes with increasing heights. When bar i is not taller than the top, the top's rectangle is bounded by i on the right and by the new top (the previous smaller) on the left. A sentinel height 0 at the end flushes the stack.
func largestRectangleArea(heights []int) int {
best := 0
var stack []int // indexes with increasing heights
for i := 0; i <= len(heights); i++ {
h := 0 // sentinel bar after the end
if i < len(heights) {
h = heights[i]
}
for len(stack) > 0 && heights[stack[len(stack)-1]] >= h {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
left := -1 // index of the previous smaller bar
if len(stack) > 0 {
left = stack[len(stack)-1]
}
best = max(best, heights[top]*(i-left-1))
}
stack = append(stack, i)
}
return best
}
Complexity. O(n) time, O(n) space. Maximal Rectangle (LeetCode 85) applies this row by row to a binary matrix.
Practice list
- Easy: Valid Parentheses (20), Implement Queue using Stacks (232), Baseball Game (682), Next Greater Element I (496)
- Medium: Min Stack (155), Evaluate Reverse Polish Notation (150), Daily Temperatures (739), Car Fleet (853), Online Stock Span (901), Decode String (394), Asteroid Collision (735), Design Circular Queue (622)
- Hard: Largest Rectangle in Histogram (84), Sliding Window Maximum (239), Basic Calculator (224), Maximal Rectangle (85)
Common pitfalls
- Popping an empty stack —
stack[len(stack)-1]panics with index out of range. Always checklenfirst (or use a sentinel). - Storing values instead of indexes on a monotonic stack, then being unable to compute distances or widths.
- Wrong strictness with duplicates (
<vs≤), which double-counts or skips equal elements. Write the tie rule down before coding. - Using
q = q[1:]for a long-lived queue: the slice keeps reallocating and holds references to popped items until it does. Symptom: steady memory growth in a worker that "only holds a few items". - Treating channels as queues — checking
len(ch)and then receiving is racy, and an unbuffered/full channel blocks the producer. Symptom: goroutine leaks and deadlocks under load. - Silently overwriting in a ring buffer that carries business data. Overwrite is for telemetry; for payment instructions, reject or apply backpressure.
- Recursion where an explicit stack is safer: deeply nested input (JSON, expression trees) recursing per level. Go's growable stacks survive deeper than most runtimes, but an explicit stack makes memory bounds visible.
Interview angle
- Naming the pattern fast matters: "this is next-greater-element, so a monotonic stack gives O(n)". Then explain the amortized bound — every index pushed and popped once.
- For sliding window maximum, interviewers often accept a heap first and then ask for O(n); know both and the trade-off.
- System design tie-ins: bounded queues and backpressure (what happens when the queue is full?), ring buffers for predictable latency, LIFO compensation order in sagas, FIFO per price level in an order book.
- Follow-ups: "Make the stack/queue thread-safe" (mutex vs channel vs lock-free — and why lock-free is rarely worth it), "Make it bounded", "What if items have priorities?" → Heaps & Priority Queues.
- Red flags: O(n²) "for each element scan right" without considering a stack, or a deque solution that cannot explain why popped elements are safe to discard.
Self-check
1. Why is a monotonic stack solution O(n) even though it has a while loop inside a for loop?
Each index is pushed exactly once and popped at most once. The total number of pops across the whole run is at most n, so the inner loop's total work is O(n), and the outer loop adds O(n). It is an amortized argument over the whole run, not per iteration.
2. In sliding window maximum, why can you discard an older smaller value when a newer larger value arrives?
The newer value stays in the window at least as long as the older one (it arrived later, so it leaves later) and it is at least as large. So for every future window that contains the old value, the new value is also present and is no smaller — the old value can never be the maximum again.
3. How would you implement a queue in Go for a BFS versus a long-running worker backlog?
BFS: a slice with q = q[1:] or a head index — simple, and the whole thing is discarded afterwards. Worker backlog: a ring-buffer deque (bounded or growable) so memory is reused, or a buffered channel if producers and consumers are different goroutines and you want blocking backpressure. container/list only if you need O(1) removal from the middle.
4. In Largest Rectangle in Histogram, what do the stack elements below a popped bar represent?
The element directly below the popped bar is the nearest bar to the left that is strictly lower (the previous smaller element), which bounds the rectangle on the left. The current index i is the first bar to the right that is not taller, bounding it on the right. Width is i − left − 1.
5. Why do ring buffers appear in latency-sensitive systems like exchanges and io_uring?
They are allocated once and reused, so there is no allocation or GC on the hot path; indexes wrap with a cheap mask; memory is contiguous and cache-friendly; and single-producer/single-consumer rings can be coordinated with sequence counters instead of locks. The cost is a fixed capacity, which forces an explicit full-buffer policy.
6. Scenario: a saga for checkout reserves inventory, charges the card, then creates the shipment. Shipment creation fails. In what order do compensations run, and which data structure models it?
Compensations run in reverse order of the completed steps — refund the card, then release the inventory — so a stack of completed steps (push on success, pop to compensate) models it exactly. Each compensation must be idempotent because the orchestrator may retry it.
Exercise
Build pkg/recent: a goroutine-safe RecentTxns that keeps the last 50 transactions per account using the Ring above (one ring per account, guarded by a sync.Mutex), plus a StockSpanner (LeetCode 901) that answers spans for a price stream with a monotonic stack.
Then benchmark Deque[int] against container/list and a q = q[1:] slice queue for 10⁶ push/pop pairs with -benchmem. Done when tests pass under -race, the benchmark table shows allocations per operation for each implementation, and you can explain the differences in terms of allocation and cache locality.
Further reading
- Go source:
runtime/chan.go— how buffered channels implement a circular queue - Martin Thompson et al., "Disruptor: High performance alternative to bounded queues for exchanging data between concurrent threads" (LMAX technical paper, 2011), and Martin Fowler, "The LMAX Architecture"
- Introduction to Algorithms (CLRS) — elementary data structures chapter
- NeetCode 150 — "Stack" section (neetcode.io)
Related
- Two Pointers & Sliding Window — windows that need a deque for extremes.
- Graphs — queues drive BFS, stacks drive iterative DFS.
- Trees & BSTs — iterative traversals with an explicit stack.
- Heaps & Priority Queues — when FIFO is not enough.
- Goroutines & Channels — channels as concurrent queues.
- Distributed Transactions: 2PC, TCC, Saga — compensation order.
- Stock Exchange — ring buffers and FIFO price levels.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).