DEPLOYEDAI-era interview training
RankBootstrapping
XP 0 / 250
0
0%
Ready
Coding Interview: Patterns & DSA · Linked Lists, Stacks & Queues · Lesson 2 of 2

Stacks, queues & the monotonic stack

7 min

A stack is last-in-first-out (LIFO); a queue is first-in-first-out (FIFO). Both give O(1) push/pop. Stacks model nesting and 'most recent'; queues model order of arrival (and drive BFS).

  • Stack: matching brackets, undo, DFS, expression evaluation, 'nearest previous' problems.
  • Queue: BFS, task scheduling, streaming/first-come order. A deque adds both ends in O(1) (sliding-window maximum).

Balanced parentheses

def is_balanced(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for c in s:
        if c in "([{":
            stack.append(c)
        elif not stack or stack.pop() != pairs[c]:
            return False
    return not stack

The monotonic stack

A monotonic stack keeps its elements in sorted order (increasing or decreasing) by popping anything that violates the order before pushing. It answers 'next greater / previous smaller element' for every position in O(n) total, because each element is pushed and popped at most once.

def next_greater(nums):
    res = [-1] * len(nums)
    stack = []                       # holds indices, values decreasing
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x     # x is the next greater for that index
        stack.append(i)
    return res
Recognize itA monotonic stack is the tell for next greater/smaller element, daily temperatures, stock span, and largest rectangle in a histogram — anything asking about the nearest larger/smaller neighbor.

◆ Lock it in

  • Stack = LIFO (nesting, 'most recent'); queue = FIFO (arrival order, BFS).
  • A monotonic stack answers next-greater/smaller for all indices in O(n).
  • Each element is pushed and popped at most once — that is what makes it linear.
Feynman drill — say it out loudExplain why a monotonic stack solves 'next greater element' in O(n) even with a nested while-loop.
Step 1 rate your confidence · Step 2 pick your answer
A monotonic stack achieves O(n) total for next-greater-element because:
Step 1 — how sure are you?