Tensorum

Stack & Queue

Bracket matching, monotonic stacks and deques, expression evaluation and queue designs.

DSAIntermediate34 hrs10 patterns · 54 problems
0%
your progress

Core idea

A monotonic stack keeps candidates in sorted order; when a new element breaks the order, everything it pops has found its answer.

Reach for it when

  • Matching brackets or nested structure
  • Next / previous greater or smaller element
  • Sliding-window maximum (monotonic deque)
  • Expression evaluation

Template

def next_greater(nums):
    res, stack = [-1] * len(nums), []   # stack of indices
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x
        stack.append(i)
    return res

Complexity

O(n) amortised — each element is pushed and popped at most once.

Common pitfalls

  • Storing values when you need indices (for widths/distances)
  • Strict vs non-strict comparison with duplicates
  • Forgetting to flush the stack at the end

Recognition cues

ParenthesesMonotonic StackMonotonic QueueQueue/Stack Design