Stack & Queue
Bracket matching, monotonic stacks and deques, expression evaluation and queue designs.
DSAIntermediate34 hrs10 patterns · 54 problems
0%
your progressCore 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 resComplexity
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
Patterns in this course
Parentheses / Bracket Matching · 7Stack Simulation / String Processing · 8Expression Evaluation · 4Stack / Queue Design · 8Iterator (Stack-based) · 2Queue Simulation · 5Monotonic Stack – Next / Previous Greater or Smaller · 9Monotonic Stack – Greedy Removal · 2Monotonic Stack – Contribution / Area · 5Monotonic Queue / Deque · 4
Recognition cues
ParenthesesMonotonic StackMonotonic QueueQueue/Stack Design