Home
DSA Patterns
Stack
Monotonic Stack Pattern
Monotonic Stack Pattern
Understand the Monotonic Stack pattern for finding Next Greater/Smaller Elements.
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
0
1
2
3
4
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
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);45 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 resultMonotonic 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
