Skip to content
Veltoryx Technologies
FreeLesson 6.1Beginner3 min readUpdated 30 October 2026

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.

text
stack = empty
for c in s:
    if c is opener:
        push matching closer
    elif stack empty or pop() != c:
        return false
return stack is empty

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

text
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 shapeRecommended techniqueTimeSpace
Matching pairs, nested openers/closersExpected closer stackO(n)O(n)
Next greater / smaller element to right or leftMonotonic stack (store indices)O(n)O(n)
Undo operations, min/max lookup in O(1)Stack storing (value, min_so_far) pairsO(1) opsO(n)
Nested repeat syntax k[str] or math RPNContext stacks (operands + operators)O(n)O(n)
Shortest turns / shortest path in unweighted graphFIFO Queue (Breadth-First Search)O(V + E)O(V)

03The golden rules

  1. In Java, always use Deque<T> stack = new ArrayDeque<>(). Never use java.util.Stack.
  2. Store indices in monotonic stacks. An index gives you both the value (nums[i]) and the distance (i - j).
  3. Refill lazily in two-stack queues. Only transfer from in to out when out is completely empty. Transferring early destroys FIFO ordering.