The pattern: stacks and queues
Master LIFO stacks, FIFO queues, monotonic stacks, and circular ring buffers to solve matching, parsing, and next-greater-element interview questions.
Stacks and queues are linear collections where elements are added and removed under strict ordering rules:
- Stack (LIFO - Last In, First Out): The last element inserted is the first one removed. Think of a stack of plates: you push onto the top, and pop from the top.
- Queue (FIFO - First In, First Out): The first element inserted is the first one removed. Think of a checkout queue: new arrivals join at the back (enqueue), and customers are served from the front (dequeue).
In Java, prefer ArrayDeque<T> over the legacy Stack<T> class (which extends Vector and carries synchronization overhead) for both stack and queue implementations.
01The core techniques
1. Bracket & Delimiter Matching (Expected Closers)
When matching nested delimiters like (), [], and {}, the most recently opened bracket must be the first one closed.
stack = empty
for c in s:
if c is opener:
push matching closer
elif stack empty or pop() != c:
return false
return stack is emptyKey insight: Push the expected closing bracket rather than the opener itself. When a closing bracket is encountered, comparing it against stack.pop() becomes a single, clean equality check.
Used for: Valid Parentheses, Minimum Add to Make Parentheses Valid.
2. Monotonic Stack (Next Greater / Warmer Element)
A monotonic stack maintains elements in strictly increasing or strictly decreasing order. It eliminates nested brute-force loops and finds the first greater (or smaller) element to the left or right in O(n) time total.
stack = empty
for i from 0 to n - 1:
while stack not empty and nums[stack.top] < nums[i]:
resolved_idx = stack.pop()
answer[resolved_idx] = nums[i]
stack.push(i)How it works:
- Elements wait on the stack because their answer has not yet appeared.
- When a larger number arrives, it simultaneously resolves all smaller waiting elements.
- Every index is pushed once and popped at most once, guaranteeing linear time.
Used for: Next Greater Element I, Daily Temperatures.
3. State & Context Saving (Two Stacks for Nested Parsing)
When expressions or strings can be arbitrarily nested (like 3[a2[c]]), inner expressions must be evaluated before outer ones can proceed.
- Use a count stack to remember how many times to repeat the current block.
- Use a string / context stack to stash the parent string built so far.
- On
[: push current state, reset working buffers. - On
]: pop state, multiply inner text, and append to the restored outer text.
Used for: Decode String, Basic Calculator.
4. Queue Design & Circular Ring Buffers
Queues can be simulated using two stacks (inbox and outbox) with amortized O(1) operations, or with a fixed-size array using modular arithmetic:
head: index of the front element.size: number of elements currently stored.- Next insertion index:
(head + size) % capacity. - Next removal index:
(head + 1) % capacity.
Used for: Implement Queue using Stacks, Design Circular Queue, Open the Lock (BFS queue).
02Which technique to use?
| Problem shape | Recommended technique | Time | Space |
|---|---|---|---|
| Matching pairs, nested openers/closers | Expected closer stack | O(n) | O(n) |
| Next greater / smaller element to right or left | Monotonic stack (store indices) | O(n) | O(n) |
| Undo operations, min/max lookup in O(1) | Stack storing (value, min_so_far) pairs | O(1) ops | O(n) |
Nested repeat syntax k[str] or math RPN | Context stacks (operands + operators) | O(n) | O(n) |
| Shortest turns / shortest path in unweighted graph | FIFO Queue (Breadth-First Search) | O(V + E) | O(V) |
03The golden rules
- In Java, always use
Deque<T> stack = new ArrayDeque<>(). Never usejava.util.Stack. - Store indices in monotonic stacks. An index gives you both the value (
nums[i]) and the distance (i - j). - Refill lazily in two-stack queues. Only transfer from
intooutwhenoutis completely empty. Transferring early destroys FIFO ordering.