Skip to content
Commitwise
Menu
Coding Interview

Monotonic stack and queue

Find the next greater or smaller element for every position in one pass with a monotonic stack, keep the maximum of a sliding window with a monotonic deque, and solve Daily Temperatures, Next Greater Element, Sliding Window Maximum and Largest Rectangle in Histogram in O(n), in Swift, Kotlin, Java and TypeScript.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“For each day, how many days until a warmer one?” “For each stock price, when is the next higher price?” “What’s the highest CPU reading in every 60-second window?” The obvious solution looks ahead from every position: two nested loops, O(n²). With 100,000 readings that’s ten billion comparisons.

A monotonic stackMonotonic stackA stack kept in sorted order of value, used to find the next or previous greater or smaller element for every position in one pass.Open in glossary → answers all of these in one pass. It keeps only the positions still waiting for an answer, in sorted order, and each new element resolves everything it beats. Every element is pushed once and popped at most once, so the whole thing is O(n). The same idea with a double-ended queue gives the maximum of a sliding window in O(n).

New to some of these? Open what you need, or skip ahead.

Basics:What are stacks and queues?

A stack is last in, first out, like a pile of plates: you push onto the top and pop from the top. A queue is first in, first out, like a line at a shop. A deque (double-ended queue) lets you add and remove at both ends. The Stacks and queues tutorial shows the right types in each language.

Basics:What does O(n) mean?

Big-O describes how the amount of work grows with the size of the input n:

  • O(1): the same work whatever the size (reading array[5]).
  • O(log n): grows very slowly (about 20 steps for a million items).
  • O(n): grows in step with the input (one pass over the array).
  • O(n²): comparing every item with every other item, which gets slow fast.

You’ll see it next to every solution, for time and for extra space (memory). The Big-O tutorial explains it properly.

Part Not started

The next greater element

The classic problem is Daily Temperatures: given daily temperatures, return for each day how many days you have to wait for a warmer temperature (0 if never).

temps  = [73, 74, 75, 71, 69, 72, 76, 73]
answer = [ 1,  1,  4,  2,  1,  1,  0,  0]

Picture people standing in a line, waiting for someone taller to arrive. Each new person looks back at the people still waiting: everyone shorter than them has found their answer (“the next taller person is me”) and leaves the line. Then the new person starts waiting too.

The people still waiting are always in decreasing order of height, because anyone shorter than a later person would already have left. That’s why it’s called a monotonic stack: its values only go one way.

For Daily Temperatures:

  • The stack holds the indexes of days still waiting for a warmer day.
  • For each new day i, while the day on top of the stack is colder, pop it: its answer is i − thatDay.
  • Then push i.

Days left on the stack at the end never got a warmer day, so their answer stays 0.

A monotonic stack maintains candidates in sorted order of value so that each new element resolves (pops) all candidates it dominates. For “next greater to the right”, scan left to right with a decreasing stack of indices; each pop assigns the popped index its answer. Variants: next smaller (increasing stack), previous greater/smaller (the element left on top after popping, or scan right to left), strict vs non-strict comparisons for duplicates, and circular arrays (iterate 2n indices modulo n). Amortized O(n): every index is pushed once and popped at most once, however the inner while loop is distributed. Storing indices, not values, gives distances and lets you look values up.

func dailyTemperatures(_ temps: [Int]) -> [Int] {
    var answer = Array(repeating: 0, count: temps.count)
    var stack: [Int] = []                          // indexes of days still waiting for a warmer day
    for (i, t) in temps.enumerated() {
        while let day = stack.last, temps[day] < t {
            stack.removeLast()
            answer[day] = i - day                  // day i is the first warmer one
        }
        stack.append(i)
    }
    return answer
}
fun dailyTemperatures(temps: IntArray): IntArray {
    val answer = IntArray(temps.size)
    val stack = ArrayDeque<Int>()                  // indexes of days still waiting for a warmer day
    for (i in temps.indices) {
        while (stack.isNotEmpty() && temps[stack.last()] < temps[i]) {
            val day = stack.removeLast()
            answer[day] = i - day                  // day i is the first warmer one
        }
        stack.addLast(i)
    }
    return answer
}
int[] dailyTemperatures(int[] temps) {
    int[] answer = new int[temps.length];
    Deque<Integer> stack = new ArrayDeque<>();     // indexes of days still waiting for a warmer day
    for (int i = 0; i < temps.length; i++) {
        while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
            int day = stack.pop();
            answer[day] = i - day;                 // day i is the first warmer one
        }
        stack.push(i);
    }
    return answer;
}
function dailyTemperatures(temps: number[]): number[] {
  const answer = new Array<number>(temps.length).fill(0);
  const stack: number[] = [];                      // indexes of days still waiting for a warmer day
  for (let i = 0; i < temps.length; i++) {
    while (stack.length > 0 && temps[stack[stack.length - 1]] < temps[i]) {
      const day = stack.pop()!;
      answer[day] = i - day;                       // day i is the first warmer one
    }
    stack.push(i);
  }
  return answer;
}

Trace the first days of the example:

Day iTempPops (answers)Stack after (temps)
073–[73]
174day 0 → 1[74]
275day 1 → 1[75]
371–[75, 71]
469–[75, 71, 69]
572day 4 → 1, day 3 → 2[75, 72]
676day 5 → 1, day 2 → 4[76]
773–[76, 73]

Days 6 and 7 are still waiting at the end, so their answers stay 0. The stack’s temperatures always go down from bottom to top.

Spot the bugSome days never find their warmer day

Tap the line with the bug.

for (i, t) in temps.enumerated() {
    if let day = stack.last, temps[day] < t {
        stack.removeLast()
        answer[day] = i - day
    }
    stack.append(i)
}
for (i in temps.indices) {
    if (stack.isNotEmpty() && temps[stack.last()] < temps[i]) {
        val day = stack.removeLast()
        answer[day] = i - day
    }
    stack.addLast(i)
}
for (int i = 0; i < temps.length; i++) {
    if (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
        int day = stack.pop();
        answer[day] = i - day;
    }
    stack.push(i);
}
for (let i = 0; i < temps.length; i++) {
  if (stack.length > 0 && temps[stack[stack.length - 1]] < temps[i]) {
    const day = stack.pop()!;
    answer[day] = i - day;
  }
  stack.push(i);
}

Exerciseeasy

Next Greater Element I

nums1 is a subset of nums2 (all values distinct). For each value in nums1, find the first greater value to its right in nums2, or −1.

nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2]   → [-1, 3, -1]
›

Run the monotonic stack over nums2 once, recording in a map: value → its next greater value.

›

Here you can store values instead of indexes, because you need the next greater value, not a distance, and values are distinct.

SolutionTry it yourself firstTime O(n + m)Space O(n)
func nextGreaterElement(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
    var next: [Int: Int] = [:]
    var stack: [Int] = []
    for n in nums2 {
        while let top = stack.last, top < n {
            next[stack.removeLast()] = n
        }
        stack.append(n)
    }
    return nums1.map { next[$0] ?? -1 }
}
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
    val next = HashMap<Int, Int>()
    val stack = ArrayDeque<Int>()
    for (n in nums2) {
        while (stack.isNotEmpty() && stack.last() < n) next[stack.removeLast()] = n
        stack.addLast(n)
    }
    return IntArray(nums1.size) { next[nums1[it]] ?: -1 }
}
int[] nextGreaterElement(int[] nums1, int[] nums2) {
    Map<Integer, Integer> next = new HashMap<>();
    Deque<Integer> stack = new ArrayDeque<>();
    for (int n : nums2) {
        while (!stack.isEmpty() && stack.peek() < n) next.put(stack.pop(), n);
        stack.push(n);
    }
    int[] result = new int[nums1.length];
    for (int i = 0; i < nums1.length; i++) result[i] = next.getOrDefault(nums1[i], -1);
    return result;
}
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
  const next = new Map<number, number>();
  const stack: number[] = [];
  for (const n of nums2) {
    while (stack.length > 0 && stack[stack.length - 1] < n) next.set(stack.pop()!, n);
    stack.push(n);
  }
  return nums1.map((v) => next.get(v) ?? -1);
}

Why the nested loop is still O(n)

Predict the output

dailyTemperatures runs on n = 1,000,000 days, sorted from hottest to coldest except the last day, which is the hottest of all. How many pops does the last day cause, and what's the total work?

Variants

QuestionScanStack orderAnswer comes from
Next greater to the rightleft → rightdecreasingthe element that pops you
Next smaller to the rightleft → rightincreasingthe element that pops you
Previous greater to the leftleft → rightdecreasingthe top after popping smaller ones
Circular array2n steps, i % nas abovepush only in the first pass
  • Next greater (right): left-to-right scan, decreasing stack of indices, while top < current: pop and answer. Next smaller: increasing stack.
  • Previous greater/smaller: the stack top after popping; circular: iterate 2n with i % n.
  • Amortized O(n): each index pushed once, popped at most once; O(n) space worst case.
  • while, not if; decide strict vs non-strict comparison for duplicates.

Check this part

  1. In Daily Temperatures, what does the stack contain?

  2. Why must the pop be a while loop?

  3. The inner while loop can pop many elements. Why is the total still O(n)?

  4. For the next smaller element to the right, which stack do you keep?

To find the next greater element for every position, scan left to right with a stack of indices still waiting for an answer, kept in decreasing order of value. Each new value pops every waiting index it beats (they've found their answer) and then waits itself. Store indices, not values, and pop in a while loop. Each index is pushed and popped once: O(n).

Part Not started

Sliding window maximum and ranges

Sliding Window Maximum: given an array and a window size k, return the maximum of every window of k consecutive elements.

nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
windows: [1 3 -1] [3 -1 -3] [-1 -3 5] [-3 5 3] [5 3 6] [3 6 7]
answer:  [3, 3, 5, 5, 6, 7]

Checking all k values in every window is O(n · k). Instead, keep a deque of indexes whose values are decreasing from front to back:

  • The front is always the window’s maximum.
  • When a new value arrives, remove from the back every value that’s smaller or equal: they can never be a maximum again, because the new value is bigger and stays in the window longer.
  • Remove the front when its index has slid out of the window.

Each index enters and leaves the deque once, so the whole pass is O(n).

A monotonic deque extends the stack idea to windows: indices in the deque have decreasing values, so the front is the window maximum; new elements evict dominated elements from the back (they’re smaller and older, so they can never be a future maximum), and expired indices leave from the front. O(n) time, O(k) space. The same structure computes window minimums (increasing deque) and appears in DP optimizations (“max of dp over the last k states”, as in Jump Game VI and Constrained Subsequence Sum).

func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
    var result: [Int] = []
    var deque: [Int] = []                          // indexes; front at `head`, values decreasing
    var head = 0
    for i in nums.indices {
        if head < deque.count && deque[head] <= i - k { head += 1 }          // front left the window
        while deque.count > head && nums[deque[deque.count - 1]] <= nums[i] {
            deque.removeLast()                     // smaller and older: never a maximum again
        }
        deque.append(i)
        if i >= k - 1 { result.append(nums[deque[head]]) }
    }
    return result
}
fun maxSlidingWindow(nums: IntArray, k: Int): IntArray {
    val result = IntArray(nums.size - k + 1)
    val deque = ArrayDeque<Int>()                  // indexes, values decreasing from front to back
    for (i in nums.indices) {
        if (deque.isNotEmpty() && deque.first() <= i - k) deque.removeFirst()     // front left the window
        while (deque.isNotEmpty() && nums[deque.last()] <= nums[i]) {
            deque.removeLast()                     // smaller and older: never a maximum again
        }
        deque.addLast(i)
        if (i >= k - 1) result[i - k + 1] = nums[deque.first()]
    }
    return result
}
int[] maxSlidingWindow(int[] nums, int k) {
    int[] result = new int[nums.length - k + 1];
    Deque<Integer> deque = new ArrayDeque<>();     // indexes, values decreasing from front to back
    for (int i = 0; i < nums.length; i++) {
        if (!deque.isEmpty() && deque.peekFirst() <= i - k) deque.pollFirst();    // front left the window
        while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
            deque.pollLast();                      // smaller and older: never a maximum again
        }
        deque.offerLast(i);
        if (i >= k - 1) result[i - k + 1] = nums[deque.peekFirst()];
    }
    return result;
}
function maxSlidingWindow(nums: number[], k: number): number[] {
  const result: number[] = [];
  const deque: number[] = [];                      // indexes; front at `head`, values decreasing
  let head = 0;
  for (let i = 0; i < nums.length; i++) {
    if (head < deque.length && deque[head] <= i - k) head++;               // front left the window
    while (deque.length > head && nums[deque[deque.length - 1]] <= nums[i]) {
      deque.pop();                                 // smaller and older: never a maximum again
    }
    deque.push(i);
    if (i >= k - 1) result.push(nums[deque[head]]);
  }
  return result;
}

Swift and TypeScript note

Swift’s standard library and JavaScript have no deque, and removing from the front of an array (removeFirst(), shift()) is O(n). The code keeps a head index instead, which makes removing from the front O(1). (Swift’s swift-collections package has a real Deque.)

Predict the output

With nums = [1, 3, -1, -3, 5, 3, 6, 7] and k = 3, which indexes are in the deque right after index 4 (value 5) is added?

Exercisemedium

Stock Span

For each day’s stock price, the span is the number of consecutive days up to and including today with a price less than or equal to today’s. Return the span for every day.

prices = [100, 80, 60, 70, 60, 75, 85]
spans  = [  1,  1,  1,  2,  1,  4,  6]
›

This is “previous greater element”: the span reaches back to the last day with a higher price.

›

Keep a decreasing stack of indexes. Pop every day with a price ≤ today’s; the span is i − top if something is left, or i + 1 if the stack is empty.

SolutionTry it yourself firstTime O(n)Space O(n)
func stockSpans(_ prices: [Int]) -> [Int] {
    var spans: [Int] = []
    var stack: [Int] = []                          // indexes with decreasing prices
    for (i, p) in prices.enumerated() {
        while let top = stack.last, prices[top] <= p { stack.removeLast() }
        spans.append(stack.last.map { i - $0 } ?? i + 1)
        stack.append(i)
    }
    return spans
}
fun stockSpans(prices: IntArray): IntArray {
    val spans = IntArray(prices.size)
    val stack = ArrayDeque<Int>()                  // indexes with decreasing prices
    for (i in prices.indices) {
        while (stack.isNotEmpty() && prices[stack.last()] <= prices[i]) stack.removeLast()
        spans[i] = if (stack.isEmpty()) i + 1 else i - stack.last()
        stack.addLast(i)
    }
    return spans
}
int[] stockSpans(int[] prices) {
    int[] spans = new int[prices.length];
    Deque<Integer> stack = new ArrayDeque<>();     // indexes with decreasing prices
    for (int i = 0; i < prices.length; i++) {
        while (!stack.isEmpty() && prices[stack.peek()] <= prices[i]) stack.pop();
        spans[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
        stack.push(i);
    }
    return spans;
}
function stockSpans(prices: number[]): number[] {
  const spans: number[] = [];
  const stack: number[] = [];                      // indexes with decreasing prices
  for (let i = 0; i < prices.length; i++) {
    while (stack.length > 0 && prices[stack[stack.length - 1]] <= prices[i]) stack.pop();
    spans.push(stack.length === 0 ? i + 1 : i - stack[stack.length - 1]);
    stack.push(i);
  }
  return spans;
}

Production puzzles

Exercisehard

Largest Rectangle in Histogram

Given bar heights of width 1, return the area of the largest rectangle that fits under the histogram.

heights = [2, 1, 5, 6, 2, 3]   → 10   (bars 5 and 6, height 5, width 2)
›

For each bar, the widest rectangle of its height extends left to the previous smaller bar and right to the next smaller bar.

›

Keep an increasing stack of indexes. When a lower bar arrives, pop taller bars: the current index is the popped bar’s right limit, and the new top of the stack is its left limit. Append a height-0 bar at the end to flush everything.

SolutionTry it yourself firstTime O(n)Space O(n)
fun largestRectangleArea(heights: IntArray): Int {
    val stack = ArrayDeque<Int>()                  // indexes with increasing heights
    var best = 0
    for (i in 0..heights.size) {
        val h = if (i == heights.size) 0 else heights[i]    // a 0-height sentinel flushes the stack
        while (stack.isNotEmpty() && heights[stack.last()] >= h) {
            val height = heights[stack.removeLast()]
            val left = if (stack.isEmpty()) -1 else stack.last()   // previous smaller bar
            best = maxOf(best, height * (i - left - 1))             // i is the next smaller bar
        }
        stack.addLast(i)
    }
    return best
}

Each bar is pushed and popped once: O(n). Without the sentinel, bars still on the stack at the end (which extend to the right edge) are never measured: for [2, 4] the answer would be 0 instead of 4. The same technique solves Maximal Rectangle in a binary matrix (run it on each row’s histogram of consecutive ones) and “sum of subarray minimums” (count how many subarrays each element is the minimum of, from its previous and next smaller elements).

Predict the output

A monitoring service keeps the max CPU over the last 60 samples for 50,000 hosts, each sampled every second, by recomputing max() over a 60-element buffer per sample. A teammate proposes the monotonic deque. What changes?

  • Sliding window max: deque of indices, decreasing values; pop front when expired (front ≤ i − k), pop back while ≤ new; front is the max. O(n), O(k). Minimum: increasing deque.
  • Swift/TypeScript: no built-in deque; use a head index or swift-collections Deque.
  • Histogram: increasing stack; on pop, right limit = current index, left limit = new top (or −1); 0-height sentinel to flush. Extends to Maximal Rectangle and sum of subarray minimums.
  • Monotonic deques also speed up DP transitions over a sliding range of states.

Check this part

  1. In the sliding window maximum, which element of the deque is the current maximum?

  2. Why remove smaller values from the back when a new value arrives?

  3. In Largest Rectangle in Histogram, when a bar is popped, what bounds its rectangle?

  4. What happens without a final 0-height sentinel?

A monotonic deque gives the maximum of every sliding window in O(n): keep indices with decreasing values, drop the front when it leaves the window, drop smaller values from the back before adding. Largest Rectangle in Histogram uses an increasing stack: when a bar is popped, the current index is its right limit and the new top is its left limit. Flush the stack at the end.

Key takeaways

  • A monotonic stack keeps positions waiting for an answer in sorted order of value.
  • Each new value pops everything it beats, with a while loop, then waits itself.
  • Store indexes when you need distances; values when you only need the value.
  • A monotonic deque gives the maximum of every sliding window in one pass.
  • Recognize the signal: next/previous greater or smaller, spans, window extremes, rectangles bounded by smaller elements.
  • Amortized O(n): count pushes and pops per element.
  • Choose stack order and strictness deliberately; use sentinels to flush.
  • Mind language gaps: no deque in Swift’s standard library or JavaScript.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.