cswork / templatesOpen the Line 500 list

STOP 07 · LINEAR STRUCTURES

Stacks, Monotonic Deques, and Heaps

Monotonic stack: next greater element O(n) time · O(n) space

Contest ratings Rating 1173–Rating 2307· median Rating 1542(13 of 34 problems rated by zerotrac)

Open the Line 500 list · stop 07 · 34 problems
Learn first
Leads to
How often asked
asked by 20 companies · in 38 reportsMeta 12, TikTok / ByteDance 5, Glean 2, LinkedIn 2, Oracle 2

Warm up with this one

LC 20Valid ParenthesesEasy
Stuck? Peek at the approach

Match bracket types with a stack, handling premature closing brackets and unmatched opening brackets.

Key points

  1. Keep indexes on the stack, not values: you can still read the value and also measure distances such as days until a warmer day.
  2. Each element is pushed and popped once, so the nested while is still O(n) overall.
  3. For the top k keep a min-heap of size k; for sliding-window maxima use a monotonic deque and drop the front once it leaves the window.

Common pitfalls

  • With duplicates, < and <= give different answers; decide whether you need strictly greater or greater-or-equal.
  • Python's heapq is a min-heap only; push negated values to get a max-heap.
  • Java's Stack class is slow and synchronized; use ArrayDeque for stacks and queues, and don't write comparators as a - b.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Monotonic stack · next greater element

Array 3, 1, 4, 1, 5, 9, 2, 6

Try your own input
30
11
42
13
54
95
26
67
·ans[0]
·ans[1]
·ans[2]
·ans[3]
·ans[4]
·ans[5]
·ans[6]
·ans[7]
CurrentDiscovered / computedAnswer
Stack bottom → top (value [index])
Empty
Index
—
Stack size
0

Top row: the array. Bottom row: each value’s next greater value to its right. The stack keeps indexes still waiting for one.

InvariantFrom bottom to top the values never increase; each index is pushed and popped once, O(n) in total.

Interactive demo · step by step

Heap · k-th largest in a stream

Stream 5, 2, 9, 1, 7, 8, 3: find the 3rd largest

Try your own input
CurrentDiscovered / computedAnswer
Still to read
5291783
k
3
Heap size
0
k-th largest
—

Keep a min-heap of at most 3 numbers: the root is the smallest one inside.

InvariantThe heap always holds the k largest numbers read so far; each push or pop costs O(log k).

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 20, with it.

Python
def next_greater(nums: list[int]) -> list[int]:
    """For each i, the first value to the right that is strictly greater, or -1."""
    ans = [-1] * len(nums)
    stack = []  # indexes still waiting; their values decrease from bottom to top
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            ans[stack.pop()] = x
        stack.append(i)
    return ans
C++
// For each i, the first value to the right that is strictly greater, or -1.
vector<int> nextGreater(const vector<int>& nums) {
    vector<int> ans(nums.size(), -1);
    vector<int> st;  // indexes still waiting; their values decrease from bottom to top
    for (int i = 0; i < (int)nums.size(); i++) {
        while (!st.empty() && nums[st.back()] < nums[i]) {
            ans[st.back()] = nums[i];
            st.pop_back();
        }
        st.push_back(i);
    }
    return ans;
}
Java
class Solution {
    // For each i, the first value to the right that is strictly greater, or -1.
    int[] nextGreater(int[] nums) {
        int[] ans = new int[nums.length];
        Arrays.fill(ans, -1);
        Deque<Integer> st = new ArrayDeque<>(); // indexes still waiting; values decrease to the top
        for (int i = 0; i < nums.length; i++) {
            while (!st.isEmpty() && nums[st.peek()] < nums[i]) ans[st.pop()] = nums[i];
            st.push(i);
        }
        return ans;
    }
}
Go
// nextGreater returns, for each i, the first value to the right that is strictly greater, or -1.
func nextGreater(nums []int) []int {
	ans := make([]int, len(nums))
	var st []int // indexes still waiting; their values decrease from bottom to top
	for i, x := range nums {
		ans[i] = -1
		for len(st) > 0 && nums[st[len(st)-1]] < x {
			ans[st[len(st)-1]] = x
			st = st[:len(st)-1]
		}
		st = append(st, i)
	}
	return ans
}

Common variants

Problems at this stop also need the 3 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Monotonic deque: sliding window maximumO(n) time (each index enters and leaves once) · O(k) space

When a sliding window must always know its maximum (or minimum): a deque of indexes whose values decrease from front to back. A new element pushes smaller ones off the back, the front is dropped once it slides out, and the front is always the maximum. LC 239 (Sliding Window Maximum); LC 862 uses the same deque over prefix sums.

Python
from collections import deque


def max_sliding_window(nums: list[int], k: int) -> list[int]:
    """Maximum of every length-k window (LC 239)."""
    dq: deque[int] = deque()  # indexes in the window, values decreasing front to back
    res = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()  # smaller values before x can never be a maximum again
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()  # the front slid out of the window
        if i >= k - 1:
            res.append(nums[dq[0]])
    return res
C++
// Maximum of every length-k window (LC 239).
vector<int> maxSlidingWindow(const vector<int>& nums, int k) {
    deque<int> dq;  // indexes in the window, values decreasing front to back
    vector<int> res;
    for (int i = 0; i < (int)nums.size(); i++) {
        while (!dq.empty() && nums[dq.back()] <= nums[i]) dq.pop_back();  // they can never be a maximum again
        dq.push_back(i);
        if (dq.front() <= i - k) dq.pop_front();  // the front slid out of the window
        if (i >= k - 1) res.push_back(nums[dq.front()]);
    }
    return res;
}
Java
class Solution {
    // Maximum of every length-k window (LC 239).
    int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> dq = new ArrayDeque<>(); // indexes in the window, values decreasing front to back
        int[] res = new int[nums.length - k + 1];
        for (int i = 0; i < nums.length; i++) {
            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast(); // they can never be a maximum again
            dq.offerLast(i);
            if (dq.peekFirst() <= i - k) dq.pollFirst(); // the front slid out of the window
            if (i >= k - 1) res[i - k + 1] = nums[dq.peekFirst()];
        }
        return res;
    }
}
Go
// maxSlidingWindow returns the maximum of every length-k window (LC 239).
func maxSlidingWindow(nums []int, k int) []int {
	var dq []int // indexes in the window, values decreasing front to back
	var res []int
	for i, x := range nums {
		for len(dq) > 0 && nums[dq[len(dq)-1]] <= x {
			dq = dq[:len(dq)-1] // they can never be a maximum again
		}
		dq = append(dq, i)
		if dq[0] <= i-k {
			dq = dq[1:] // the front slid out of the window
		}
		if i >= k-1 {
			res = append(res, nums[dq[0]])
		}
	}
	return res
}
Size-k min-heap for the k-th largestO(n log k) time · O(k) space

When only the k largest matter (the k-th largest, the top k frequent, the k-th largest in a stream): keep a min-heap of size k whose top is the weakest of them, and replace it only when a new value beats it. Cheaper than sorting everything: O(n log k). LC 215 (Kth Largest Element in an Array), LC 703, LC 373.

Python
import heapq


def kth_largest(nums: list[int], k: int) -> int:
    """The k-th largest value (LC 215), with a size-k min-heap."""
    heap: list[int] = []  # the k largest so far; heap[0] is the smallest of them
    for x in nums:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)  # x beats the weakest of the top k
    return heap[0]
C++
// The k-th largest value (LC 215), with a size-k min-heap.
int kthLargest(const vector<int>& nums, int k) {
    priority_queue<int, vector<int>, greater<int>> heap;  // the k largest so far; top is the smallest
    for (int x : nums) {
        if ((int)heap.size() < k) heap.push(x);
        else if (x > heap.top()) {
            heap.pop();  // x beats the weakest of the top k
            heap.push(x);
        }
    }
    return heap.top();
}
Java
class Solution {
    // The k-th largest value (LC 215), with a size-k min-heap.
    int kthLargest(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>(); // the k largest so far; peek() is the smallest
        for (int x : nums) {
            if (heap.size() < k) heap.offer(x);
            else if (x > heap.peek()) {
                heap.poll(); // x beats the weakest of the top k
                heap.offer(x);
            }
        }
        return heap.peek();
    }
}
Go
import "container/heap"

// minHeap is a min-heap of ints for container/heap.
type minHeap []int

func (h minHeap) Len() int           { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *minHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

// kthLargest returns the k-th largest value (LC 215), with a size-k min-heap.
func kthLargest(nums []int, k int) int {
	h := &minHeap{} // the k largest so far; (*h)[0] is the smallest
	for _, x := range nums {
		if h.Len() < k {
			heap.Push(h, x)
		} else if x > (*h)[0] {
			(*h)[0] = x // x beats the weakest of the top k
			heap.Fix(h, 0)
		}
	}
	return (*h)[0]
}
Expression stack: fold * and / at once, push + and -O(n) time · O(n) space

To evaluate + - * / without parentheses (LC 227, Basic Calculator II): when a number ends, look at the operator before it; + and - push the signed number, * and / fold it into the top at once, and the answer is the sum of the stack. LC 224 and LC 772 add parentheses by recursing or pushing a level per bracket.

Python
def calculate(s: str) -> int:
    """+ - * / over non-negative integers, no parentheses (LC 227); / truncates toward zero."""
    stack: list[int] = []  # signed terms to add up; * and / fold into the last one
    num, op = 0, "+"  # op: the operator before num
    for i, c in enumerate(s):
        if c.isdigit():
            num = num * 10 + int(c)
        if (not c.isdigit() and c != " ") or i == len(s) - 1:  # an operator or the end closes num
            if op == "+":
                stack.append(num)
            elif op == "-":
                stack.append(-num)
            elif op == "*":
                stack.append(stack.pop() * num)
            else:
                top = stack.pop()
                stack.append(abs(top) // num * (1 if top >= 0 else -1))  # truncate toward zero
            op, num = c, 0
    return sum(stack)
C++
// + - * / over non-negative integers, no parentheses (LC 227); / truncates toward zero.
long long calculate(const string& s) {
    vector<long long> stack;  // signed terms to add up; * and / fold into the last one
    long long num = 0;
    char op = '+';  // the operator before num
    for (size_t i = 0; i < s.size(); i++) {
        char c = s[i];
        if (isdigit(c)) num = num * 10 + (c - '0');
        if ((!isdigit(c) && c != ' ') || i == s.size() - 1) {  // an operator or the end closes num
            if (op == '+') stack.push_back(num);
            else if (op == '-') stack.push_back(-num);
            else if (op == '*') stack.back() *= num;
            else stack.back() /= num;  // C++ division truncates toward zero
            op = c;
            num = 0;
        }
    }
    return accumulate(stack.begin(), stack.end(), 0LL);
}
Java
class Solution {
    // + - * / over non-negative integers, no parentheses (LC 227); / truncates toward zero.
    long calculate(String s) {
        Deque<Long> stack = new ArrayDeque<>(); // signed terms to add up; * and / fold into the last one
        long num = 0;
        char op = '+'; // the operator before num
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) num = num * 10 + (c - '0');
            if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) { // an operator or the end closes num
                if (op == '+') stack.push(num);
                else if (op == '-') stack.push(-num);
                else if (op == '*') stack.push(stack.pop() * num);
                else stack.push(stack.pop() / num); // Java division truncates toward zero
                op = c;
                num = 0;
            }
        }
        long total = 0;
        for (long term : stack) total += term;
        return total;
    }
}
Go
// calculate evaluates + - * / over non-negative integers, no parentheses (LC 227).
func calculate(s string) int {
	var stack []int // signed terms to add up; * and / fold into the last one
	num, op := 0, byte('+') // op: the operator before num
	for i := 0; i < len(s); i++ {
		c := s[i]
		digit := c >= '0' && c <= '9'
		if digit {
			num = num*10 + int(c-'0')
		}
		if (!digit && c != ' ') || i == len(s)-1 { // an operator or the end closes num
			switch op {
			case '+':
				stack = append(stack, num)
			case '-':
				stack = append(stack, -num)
			case '*':
				stack[len(stack)-1] *= num
			default:
				stack[len(stack)-1] /= num // Go division truncates toward zero
			}
			op, num = c, 0
		}
	}
	total := 0
	for _, term := range stack {
		total += term
	}
	return total
}

Why it works

  1. If index i is still on the stack when x arrives, nothing between i and here was greater than nums[i] (it would have popped i), so the x that pops i is its next greater element.
  2. Amortised O(n): each index is pushed exactly once and popped at most once, so all the while loops together pop at most n times.
  3. A size-k min-heap: its top is the smallest of the k kept values, so a new value can belong to the top k only if it beats the top, and replacing the top never evicts a true top-k value.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
找右边第一个更大的数,我用单调栈,栈里存下标,对应的值从底到顶递减。新元素到来时,把比它小的都弹出,并把它们的答案记为这个新元素。一个下标还留在栈里,说明中间没有更大的数,所以弹出时记下的一定是第一个更大的。每个下标只进出栈各一次,所以虽然有嵌套 while,总复杂度还是 O(n)。
English
For the next greater element I keep a monotonic stack of indexes whose values decrease from bottom to top. When a new value arrives, I pop every smaller one and record the new value as its answer. An index still on the stack means nothing in between was larger, so the value that pops it really is the first greater one. Each index is pushed and popped at most once, so despite the nested loop the total is O(n).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. Building a binary heap from n unordered elements bottom-up (sift down from the last internal node back to the root) takes:
  2. To keep the k largest numbers of a stream with a heap, the standard approach is:
  3. Which of these is the classic use of a monotonic stack?
  4. What is the time complexity of this code (n = len(a), tightest bound)?
    def next_greater(a):
        res = [-1] * len(a)
        stack = []
        for i, x in enumerate(a):
            while stack and a[stack[-1]] < x:
                res[stack.pop()] = x
            stack.append(i)
        return res
  5. What is the worst-case time complexity (n = len(a))?
    import heapq
    
    def build(a):
        h = []
        for x in a:
            heapq.heappush(h, x)
        return h

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 34 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 6

#ProblemApproachRating
20Valid ParenthesesMatch bracket types with a stack, handling premature closing brackets and unmatched opening brackets.
150Evaluate Reverse Polish NotationEvaluate postfix expressions with an operand stack, preserving operand order for noncommutative operations.
1047Remove All Adjacent Duplicates In StringImplement adjacent cancellation with a stack so newly adjacent characters can also be removed.Rating 1286
496Next Greater Element IMaintain a monotonic stack from right to left to find each value's next greater element.
921Minimum Add to Make Parentheses ValidCount unmatched opening and closing parentheses rather than checking only their total difference.Rating 1242
1046Last Stone WeightRepeatedly remove the two largest elements and reinsert their difference to practice priority-queue updates.Rating 1173

Core 16

#ProblemApproachRating
71Simplify PathInterpret path components as current directory, parent directory, or ordinary names to maintain a canonical path stack.
1209Remove All Adjacent Duplicates in String IIAttach repetition counts to stack entries to perform cascading removals whenever a run reaches k.Rating 1542
394Decode StringSave the preceding string and repeat count at each bracket to restore nested decoding contexts.
224Basic CalculatorTrack signs and bracket contexts to evaluate addition and subtraction, including unary minus.
227Basic Calculator IIRespect multiplication and division precedence over addition and subtraction, and specify integer-division truncation.
739Daily TemperaturesStore indices in the stack and calculate waiting distances when the first warmer temperature is found.
503Next Greater Element IISimulate a circular array with two traversals without writing answers for fictitious second-pass positions.
962Maximum Width RampBuild a decreasing stack of potential left endpoints, then scan backward for the furthest matching right endpoints.Rating 1608
402Remove K DigitsMaintain a monotonic digit stack within the deletion budget, handling remaining tail deletions and leading zeros.
735Asteroid CollisionHandle only collisions between approaching asteroids, distinguishing destruction, survival, and mutual cancellation.
946Validate Stack SequencesSimulate pushes and greedily match available pops to verify the entire pop-order constraint.Rating 1462
1249Minimum Remove to Make Valid ParenthesesRecord unmatched-parenthesis positions and retain the other characters to produce a valid result.Rating 1657
1190Reverse Substrings Between Each Pair of ParenthesesPair parentheses first, then switch traversal direction to reverse nested content without repeatedly copying substrings.Rating 1486
215Kth Largest Element in an ArrayMaintain candidates in a size-k heap and compare this with quickselect's expected linear-time approach.
1834Single-Threaded CPUAdvance the simulation by arrival time and choose the next task by processing time and then index.Rating 1798
239Sliding Window MaximumUse a monotonic deque to remove both expired elements and dominated candidates.

Advanced 12

#ProblemApproachRating
772Basic Calculator III 🔒Combine nested parentheses with operator precedence to implement a complete expression parser.
726Number of AtomsMaintain atom counts at each nesting level, apply multidigit multipliers, and produce a canonical output order.
84Largest Rectangle in HistogramFind each bar's left and right extension boundaries, handling equal heights and sentinels.
85Maximal RectangleConvert each binary-matrix row into a histogram and reuse the maximum-rectangle algorithm, resetting heights at zeros.
907Sum of Subarray MinimumsUse a monotonic stack to count each element's contribution as a minimum, assigning equal values consistently.Rating 1976
2104Sum of Subarray RangesCompute subarray maximum and minimum contributions separately, with consistent boundary rules for duplicates.Rating 1504
456132 PatternScan backward with a candidate third element and a monotonic stack to detect a nonadjacent 132 pattern.
316Remove Duplicate LettersCombine remaining character counts with stack membership to build the lexicographically smallest subsequence of distinct characters.
2402Meeting Rooms IIIManage free rooms and occupied-room finishing times separately, correctly delaying meetings and ordering simultaneous events.Rating 2093
373Find K Pairs with Smallest SumsView sorted pair sums as multiple sorted sequences and expand candidates incrementally with a heap.
632Smallest Range Covering Elements from K ListsTrack a current candidate from each list and the overall maximum to find the shortest range covering all lists.
862Shortest Subarray with Sum at Least KMaintain a monotonic deque of prefix sums when negative values make an ordinary sliding window invalid.Rating 2307

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.