Monotonic stack
32 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A monotonic stack maintains elements in strictly increasing or strictly decreasing order. It solves next greater element and span problems in linear time.
The monotonic stack pattern: Next Greater Element
A monotonic stack keeps its elements always increasing or always decreasing, popping elements that break the order; it finds the next greater or smaller element in O(n).
A monotonic stack keeps indexes whose values are always decreasing. A new value pops every smaller value on top, and for each popped index the new value is its next greater element.
- Iterate through the array from left to right.
- While stack is not empty and current value > array[stack.peek()], pop.
- Record current value as the answer for the popped index.
- Push the current index onto the stack.
Next Greater Element Trace on [4, 5, 2, 10, 8]
Step 1 of 9
- current
- 4
- 0
Example 1 · Brute force: scan to the right for every element (O(n^2) time, O(1) extra space)
import java.util.Arrays;
public class NextGreaterBruteDemo { static int[] nextGreater(int[] nums) { int[] res = new int[nums.length]; Arrays.fill(res, -1); for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] > nums[i]) { res[i] = nums[j]; break; } } } return res; }
public static void main(String[] args) { int[] nums = {4, 5, 2, 10, 8}; System.out.println(Arrays.toString(nextGreater(nums))); }}[5, 10, 10, -1, -1]
What this code does
- For each index
ithe inner loop looks right until it finds a bigger value, andbreakstops at the first one. - A falling sequence such as 9, 8, 7, 6 makes every inner loop run to the end: about n * n / 2 comparisons.
- The monotonic stack in the next example gives each element its answer while scanning once.
Example 2 · Optimal: monotonic stack (O(n) time, O(n) space)
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
public class NextGreaterElementDemo { public static int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] res = new int[n]; Arrays.fill(res, -1); Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) { while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) { int prev = stack.pop(); res[prev] = nums[i]; } stack.push(i); } return res; }
public static void main(String[] args) { int[] nums = {4, 5, 2, 10, 8}; System.out.println(Arrays.toString(nextGreaterElements(nums))); }}[5, 10, 10, -1, -1]
What this code does
- 4 finds 5 as next greater element.
- 5 and 2 find 10.
- 10 and 8 have no greater elements to the right and remain -1.
Nested loops scan right from every index and take O(n²) time (the first example). The stack gives the same answers in one O(n) pass.
On [4, 5, 2, 10, 8] the result is [5, 10, 10, -1, -1]: indexes still on the stack at the end have no greater element to their right, so they stay -1.
- Monotonic decreasing stack: stores elements or indices in decreasing order.
- Trigger condition: incoming element is strictly greater than the top element.
- Resolution: incoming element resolves the answer for all smaller popped items.
- Unresolved items: remaining stack elements have no greater element to their right.
Daily temperatures and stock span problems
The Daily Temperatures problem asks how many days to wait for a warmer temperature.
Store day indices on the stack.
When temperature t[i] > t[stack.peek()], the wait distance is i - stack.pop().
Unresolved colder days remain 0.
Example 3 · Daily Temperatures Distance Calculation
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
public class DailyTemperaturesDemo { public static int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] ans = new int[n]; Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) { while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int prevDay = stack.pop(); ans[prevDay] = i - prevDay; } stack.push(i); } return ans; }
public static void main(String[] args) { int[] temps = {73, 74, 75, 71, 69, 72, 76, 73}; System.out.println(Arrays.toString(dailyTemperatures(temps))); }}[1, 1, 4, 2, 1, 1, 0, 0]
What this code does
- Day 0 waits 1 day for 74.
- Day 2 waits 4 days until 76 arrives at index 6.
- The algorithm computes wait intervals in O(n) time.
Example 4 · Online Stock Span Tracker
import java.util.ArrayDeque;import java.util.Deque;
public class StockSpannerDemo { static class StockSpanner { static class Pair { int price, span; Pair(int p, int s) { price = p; span = s; } } private final Deque<Pair> stack = new ArrayDeque<>();
public int next(int price) { int span = 1; while (!stack.isEmpty() && stack.peek().price <= price) { span += stack.pop().span; } stack.push(new Pair(price, span)); return span; } }
public static void main(String[] args) { StockSpanner sp = new StockSpanner(); int[] prices = {100, 80, 60, 70, 60, 75, 85}; for (int p : prices) { System.out.print(sp.next(p) + " "); } System.out.println(); }}1 1 1 2 1 4 6
What this code does
- Day with price 70 combines spans of 70 and 60, returning 2.
- Day with price 85 absorbs 75, 60, 70, 60, 80, returning 6.
- Monotonic aggregation delivers amortized O(1) per call.
The Stock Span problem asks for consecutive days of lower or equal stock price.
Maintain a decreasing stack of price indices.
Pop all indices with price less than or equal to current price.
The span is currentIndex - stack.peek(), or currentIndex + 1 if the stack becomes empty. For temperatures [73, 74, 75, 71, 69, 72]:
Day 0 (73) pushes 0.
Day 1 (74) sees 74 > 73, popping 0 with wait 1 - 0 = 1 day.
Day 2 (75) pops 1 with wait 2 - 1 = 1 day.
Day 5 (72) pops day 4 (69) with wait 5 - 4 = 1, and day 3 (71) with wait 5 - 3 = 2.
Remember:
- Daily temperatures: distance equals
currentIndex - poppedIndex. - Stock span: distance equals
currentIndex - stack.peek()after popping smaller prices. - Index storage: storing indices allows computing both values and distances.
Predict the output
Trace Daily Temperatures
Read the code and pick what it prints.
Round 1 of 2
Why monotonic stacks run in linear O(n) time
A while loop nested inside a for loop often signals O(n²) quadratic complexity.
However, in a monotonic stack, every array index is pushed onto the stack exactly once.
Furthermore, each index is popped from the stack at most once. The while loop runs at most n times across the entire algorithm, proving amortized O(n) time.
- Maximum pushes: exactly n pushes.
- Maximum pops: at most n pops.
- Total operations: bounded by 2n, confirming strict O(n) time.
Next step
Check your understanding
10 quick questions