Skip to main content

LeetCode Patterns

Monotonic Stack Pattern

The Monotonic Stack pattern maintains a stack whose elements stay in strictly increasing or decreasing order. When a new element violates that order, the stack pops until the order is restored, and each pop emits an answer for the popped element. This drops Next Greater Element and span-style problems from O(n^2) to O(n) because each item is pushed and popped at most once.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

Time
O(n)
Space
O(n)

When to use Monotonic Stack

  • You need the next (or previous) greater or smaller element for every index in an array.
  • The problem asks for the largest rectangle, span, or area bounded by heights / temperatures / prices.
  • You can phrase the question as 'for each index i, find the closest j with property P' and P is a monotonic comparison.
  • A brute-force O(n^2) sweep over every (i, j) pair would TLE, but each element only needs to be 'seen' a constant number of times.
  • You are simulating a stack-based parser (valid parentheses, expression evaluation) where order constraints matter.

Template

function nextGreaterElement(nums) {
  const n = nums.length;
  const result = new Array(n).fill(-1);
  const stack = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && nums[stack[stack.length - 1]] < nums[i]) {
      const j = stack.pop();
      result[j] = nums[i];
    }
    stack.push(i);
  }
  return result;
}

Example LeetCode problems

#ProblemDifficultyFrequency
739Daily Temperaturesmediumfoundational
496Next Greater Element Ieasyfoundational
503Next Greater Element IImediumfrequently asked
84Largest Rectangle in Histogramhardcompany favorite
42Trapping Rain Waterhardcompany favorite
85Maximal Rectanglehardclassic
907Sum of Subarray Minimumsmediumfrequently asked
901Online Stock Spanmediumcompany favorite

Common mistakes

  • Pushing values onto the stack instead of indices, then losing the ability to write the answer back to result[j] when an item pops.
  • Using `<=` vs `<` in the comparison without thinking — strict comparison gives the strictly next greater, while non-strict gives the next greater-or-equal, and many problems hinge on this distinction.
  • Forgetting the circular wraparound on Next Greater Element II — iterate 2n times and index with i % n so each element sees every other element.
  • On Largest Rectangle in Histogram, not appending a sentinel zero (or pretending the array has a virtual zero at the end) to flush remaining items out of the stack.
  • Confusing 'next greater on the right' with 'previous greater on the left' — same template, but the iteration direction (and sometimes the comparison sign) flips.

Frequently asked questions

Why is the total work O(n) when there is a nested while loop?

Each index is pushed onto the stack exactly once and popped at most once across the entire run. The inner while loop's total iterations sum to at most n over all outer iterations, so the amortized cost per element is O(1) and the whole sweep is O(n).

Should the stack hold values or indices?

Almost always indices. Indices let you compute distances (Daily Temperatures wants the gap, not the value), write into a result array at the right position, and still recover the value via nums[stack.top()] when needed. Storing only values throws away that capability.

How does Largest Rectangle in Histogram use a monotonic stack?

Maintain a stack of indices with strictly increasing bar heights. When a shorter bar arrives, pop each taller bar in turn and compute the rectangle whose height is the popped bar and whose width spans from the new previous-shorter on the stack to the current index. Each pop yields a candidate area; track the max.

When should I use a deque instead of a stack?

Use a deque when you also need to evict items from the front, typically in sliding-window maximum problems where elements expire as the window slides. A pure 'next greater' question only pops the back, so a stack is enough.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Monotonic Stack pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →