← DSA roadmap

Topic 14 of 21 · Advanced

Monotonic Stack & Deque

Keep a stack/deque sorted to answer 'next greater' and 'window max' in O(n).

Concept

A monotonic stack stays increasing or decreasing. When a new element breaks the order, you pop — and each pop is the moment you discover an answer for the popped element (e.g. its next greater element).

A monotonic deque keeps candidates for a sliding-window maximum: drop smaller elements from the back, drop expired indices from the front. The front is always the window max.

Every element is pushed and popped at most once, so total time is O(n) even with a nested while loop.

Complexity

OperationTimeSpace
Next greater element (all)O(n)O(n)
Sliding window maximumO(n)O(k)
Largest rectangle in histogramO(n)O(n)

Code (Python)

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

from collections import deque
def max_sliding_window(nums, k):
    dq, out = deque(), []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

Remember

  • Store indices, not values — you often need distances.
  • 'Next greater/smaller', 'span', 'temperatures' → monotonic stack.
  • 'Max/min of every window' → monotonic deque.

Practice these interview problems

  • Daily Temperatures
  • Largest Rectangle in Histogram
  • Trapping Rain Water
  • Sliding Window Maximum
Practice with the AI mentor

Lesson test

Take an 8-question test on “Monotonic Stack & Deque” — concepts, output prediction, bug spotting and interview questions.