Browse curriculum

Monotonic Stack Pattern

Understand the Monotonic Stack pattern for finding Next Greater/Smaller Elements.

Medium
10 min

What is a Monotonic Stack?

A Monotonic Stack is a stack where elements are always sorted (either increasing or decreasing). It allows us to solve problems related to Next Greater Element or Next Smaller Element in O(N) time.

  • Monotonic Increasing: [1, 2, 5, 8]. Used to find the Next Smaller Element.
  • Monotonic Decreasing: [10, 8, 4, 1]. Used to find the Next Greater Element.

How It Works

We iterate through an array. Before pushing a new element X, we Pop all elements from the stack that violate the monotonic property.

Example (Next Greater Element):
We want a Decreasing Stack. While X is greater than the value on top, X is the "Next Greater Element" for that top: pop it and record X as its answer. Stop when the stack is empty or its top is at least X, then push X. The stack stores indices, so each answer is written back to the position it belongs to.

Interactive Visualization

STACK VALUES DECREASE BOTTOM → TOP

FILL -1

nums · result

2
-1

0

1
-1

1

5
-1

2

3
-1

3

6
-1

4

4
-1

5

stack · waiting

empty

Waiting

0

Resolved

0

 

Fill result with -1: a value with no greater value after it keeps -1

Next

Read 2 at 0

Free preview: the first 6 of 18 steps

Array

Run the template below on an array: each value pops the smaller values waiting on the stack and is written in as their answer. The stack's values always decrease from bottom to top.

Monotonic Stack Pattern Dry Run

Input: [2, 1, 5, 3, 6, 4]

i Value Popped (answer written) Stack after (values) result
0 2 - [2] [-1, -1, -1, -1, -1, -1]
1 1 - [2, 1] [-1, -1, -1, -1, -1, -1]
2 5 1 → 5, then 2 → 5 [5] [5, 5, -1, -1, -1, -1]
3 3 - [5, 3] [5, 5, -1, -1, -1, -1]
4 6 3 → 6, then 5 → 6 [6] [5, 5, 6, 6, -1, -1]
5 4 - [6, 4] [5, 5, 6, 6, -1, -1]

6 and 4 are still on the stack at the end, so they keep -1.

Edge Cases & Common Mistakes

  • Decreasing input: Nothing is ever popped, and every answer stays -1.
  • Equal values: nums[top] < nums[i] is strict, so an equal value is not a next greater element. Use <= if the problem asks for greater-or-equal.
  • Store indices, not values: The answer has to be written to the position it belongs to.
  • Next smaller instead: Flip the comparison to > and the stack increases from bottom to top.

The Pattern Template

Template for the next greater element of every position, or -1 when there is none.

Monotonic Stack Pattern Code
1function nextGreater(nums) {
2 const stack = [];
3 const result = new Array(nums.length).fill(-1);
4
5 for (let i = 0; i < nums.length; i++) {
6 while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {
7 const idx = stack.pop();
8 result[idx] = nums[i];
9 }
10 stack.push(i);
11 }
12 return result;
13}

Monotonic Stack Pattern in Python, Java, C++, TypeScript and C

Monotonic Stack Pattern in Python
def nextGreater(nums):
    stack = []
    result = [-1] * len(nums)

    for i, num in enumerate(nums):
        while stack and nums[stack[-1]] < num:
            idx = stack.pop()
            result[idx] = num
        stack.append(i)
    return result
Monotonic Stack Pattern in Java
public int[] nextGreater(int[] nums) {
    Deque<Integer> stack = new ArrayDeque<>();
    int[] result = new int[nums.length];
    Arrays.fill(result, -1);

    for (int i = 0; i < nums.length; i++) {
        while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
            int idx = stack.pop();
            result[idx] = nums[i];
        }
        stack.push(i);
    }
    return result;
}
Monotonic Stack Pattern in C++
vector<int> nextGreater(vector<int>& nums) {
    stack<int> st;
    vector<int> result(nums.size(), -1);

    for (int i = 0; i < (int) nums.size(); i++) {
        while (!st.empty() && nums[st.top()] < nums[i]) {
            int idx = st.top(); st.pop();
            result[idx] = nums[i];
        }
        st.push(i);
    }
    return result;
}
Monotonic Stack Pattern in TypeScript
function nextGreater(nums: number[]): number[] {
    const stack: number[] = [];
    const result: number[] = new Array(nums.length).fill(-1);

    for (let i = 0; i < nums.length; i++) {
        while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {
            const idx = stack.pop()!;
            result[idx] = nums[i];
        }
        stack.push(i);
    }
    return result;
}
Monotonic Stack Pattern in C
int* nextGreater(int* nums, int size, int* returnSize) {
    int* stack = malloc(size * sizeof(int));
    int top = -1;
    int* result = malloc(size * sizeof(int));
    for (int i = 0; i < size; i++) result[i] = -1;

    for (int i = 0; i < size; i++) {
        while (top >= 0 && nums[stack[top]] < nums[i]) {
            int idx = stack[top--];
            result[idx] = nums[i];
        }
        stack[++top] = i;
    }
    free(stack);
    *returnSize = size;
    return result;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Fill with -1

    Start every answer as -1 and the stack empty.

  2. Pop smaller values

    While the value on top is smaller than the current value, pop it and record the current value as its answer.

  3. Push the index

    Push the current index; values left on the stack keep -1.

Frequently asked questions

What is a monotonic stack?

A stack whose values stay in sorted order from bottom to top. Before pushing, you pop every value that would break the order, and each pop is the moment that value gets its answer.


How does it find the next greater element?

Keep indices whose values decrease from bottom to top. When a value larger than the top arrives, it is the next greater element for every smaller value it pops.


Why is a monotonic stack O(n)?

Every index is pushed once and popped at most once, so the while loop runs at most n times across the whole pass.

New to the technique behind this problem? Watch it run step by step:

Stack Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description