Monotonic structures maintain elements in sorted order (increasing or decreasing) while scanning once. They are ideal for questions that ask for nearest greater or smaller element, range influence, or max/min over sliding windows.

Pattern 1: Monotonic stack (next greater element)

Maintain decreasing stack of indices. When current value is greater than top, resolve answers.

export function nextGreater(nums: number[]): number[] {
  const result = Array.from({ length: nums.length }, () => -1);
  const stack: number[] = []; // stores indices, values decrease from bottom to top

  for (let i = 0; i < nums.length; i++) {
    while (stack.length > 0 && nums[i]! > nums[stack[stack.length - 1]!]!) {
      const index = stack.pop()!;
      result[index] = nums[i]!;
    }
    stack.push(i);
  }

  return result;
}

Every index is pushed and popped at most once, so runtime is O(n).

Pattern 2: Largest rectangle in histogram

Use increasing stack of indices. When height drops, popped bar gets its maximal width.

export function largestRectangleArea(heights: number[]): number {
  const stack: number[] = [];
  let best = 0;

  for (let i = 0; i <= heights.length; i++) {
    const current = i === heights.length ? 0 : heights[i]!;
    while (stack.length > 0 && current < heights[stack[stack.length - 1]!]!) {
      const h = heights[stack.pop()!]!;
      const left = stack.length === 0 ? -1 : stack[stack.length - 1]!;
      const width = i - left - 1;
      best = Math.max(best, h * width);
    }
    stack.push(i);
  }

  return best;
}

Pattern 3: Monotonic queue (sliding window maximum)

Maintain deque of indices with decreasing values. Front is max of current window.

export function maxSlidingWindow(nums: number[], k: number): number[] {
  const deque: number[] = [];
  const result: number[] = [];

  for (let i = 0; i < nums.length; i++) {
    while (deque.length > 0 && deque[0]! <= i - k) deque.shift();
    while (deque.length > 0 && nums[deque[deque.length - 1]!]! <= nums[i]!) deque.pop();
    deque.push(i);
    if (i >= k - 1) result.push(nums[deque[0]!]!);
  }

  return result;
}

How to identify monotonic opportunities

Signal phrases:

  • "Next greater/smaller element"
  • "For each index, nearest index to left/right satisfying condition"
  • "Max/min in every window of size k"
  • "Largest area/range controlled by nearest smaller boundary"

Common mistakes

  • Storing values instead of indices (you lose position info)
  • Wrong comparator (< vs <=) causing duplicate handling bugs
  • Forgetting to evict out-of-window indices in monotonic queue
  • Missing sentinel pass in histogram problems

Practice set

  • Next greater element I and II
  • Daily temperatures
  • Largest rectangle in histogram
  • Maximal rectangle
  • Sliding window maximum

Monotonic structures are mostly about invariants. If you can state the invariant and preserve it in each step, the code is usually short and correct.