1. Home
  2. Data Structures
  3. Monotonic Stack (Next Greater Element)

Monotonic Stack (Next Greater Element)

Keep a stack in sorted order and answer "what is the next bigger value?" for every element in a single pass.

Interactive 3DIntermediate11 min readDSAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

The monotonic stack answers “what is the next greater element?” for every position in O(n). Enter numbers and press Run.

Pseudocode

  1. stack ← empty; result[0..n−1] ← −1
  2. for i ← 0 to n − 1:
  3. while stack is not empty and a[stack.top] < a[i]:
  4. result[stack.top] ← a[i] // a[i] is the next greater element
  5. stack.pop()
  6. stack.push(i)
  7. indices left on the stack keep result = −1
Read this model as text · 23 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. The monotonic stack answers “what is the next greater element?” for every position in O(n). Enter numbers and press Run.
  2. For every element we want the next greater element to its right. A stack of indices, kept in decreasing order of value, finds all answers in one pass.
  3. Look at a[0] = 4. The stack is empty.
  4. Push index 0. Values on the stack are now 4: always decreasing from bottom to top.
  5. Look at a[1] = 5. The top of the stack is a[0] = 4.
  6. 4 < 5, so 5 is the next greater element of a[0] = 4. Record it and pop index 0.
  7. Push index 1. Values on the stack are now 5: always decreasing from bottom to top.
  8. Look at a[2] = 2. The top of the stack is a[1] = 5.
  9. Push index 2. Values on the stack are now 5 ≥ 2: always decreasing from bottom to top.
  10. Look at a[3] = 10. The top of the stack is a[2] = 2.
  11. 2 < 10, so 10 is the next greater element of a[2] = 2. Record it and pop index 2.
  12. 5 < 10, so 10 is the next greater element of a[1] = 5. Record it and pop index 1.
  13. Push index 3. Values on the stack are now 10: always decreasing from bottom to top.
  14. Look at a[4] = 8. The top of the stack is a[3] = 10.
  15. Push index 4. Values on the stack are now 10 ≥ 8: always decreasing from bottom to top.
  16. Look at a[5] = 6. The top of the stack is a[4] = 8.
  17. Push index 5. Values on the stack are now 10 ≥ 8 ≥ 6: always decreasing from bottom to top.
  18. Look at a[6] = 12. The top of the stack is a[5] = 6.
  19. 6 < 12, so 12 is the next greater element of a[5] = 6. Record it and pop index 5.
  20. 8 < 12, so 12 is the next greater element of a[4] = 8. Record it and pop index 4.
  21. 10 < 12, so 12 is the next greater element of a[3] = 10. Record it and pop index 3.
  22. Push index 6. Values on the stack are now 12: always decreasing from bottom to top.
  23. Indices still on the stack have nothing greater to their right, so their answer is −1. Every index was pushed once and popped at most once: O(n) in total.

Try this in the 3D model

  • Run the default array 4, 5, 2, 10, 8, 6, 12. Which element pops the most values at once?
  • Press Decreasing and run it. Why is nothing ever popped, and what is every answer?
  • Try an increasing array such as 1, 2, 3, 4, 5. How deep does the stack get?
  • Count the pushes and pops for a random array. Is the total always at most 2n?

The problem

For every element of an array, find the next element to its right that is strictly greater, or −1 if none exists.

For [4, 5, 2, 10, 8, 6, 12] the answer is [5, 10, 10, 12, 12, 12, −1].

The brute-force way compares every pair in O(n²). A stack does it in O(n).

The idea

Keep a stack of indices whose answer is still unknown. When a new value a[i] arrives:

  1. While the value on top of the stack is smaller than a[i], then a[i] is its next greater element. Record it and pop.
  2. Push i.

Because we pop every smaller value before pushing, the values on the stack are always decreasing from bottom to top. That ordering is what the word monotonic means.

stack ← empty;   result ← all −1
for i from 0 to n − 1:
    while stack is not empty and a[stack.top] < a[i]:
        result[stack.top] ← a[i]
        stack.pop()
    stack.push(i)

Why it is O(n)

Each index is pushed exactly once and popped at most once, so the inner while loop does at most n pops over the whole run. Total work is at most 2n.

Code

def next_greater(a):
    result = [-1] * len(a)
    stack = []                       # indices, values decreasing
    for i, x in enumerate(a):
        while stack and a[stack[-1]] < x:
            result[stack.pop()] = x
        stack.append(i)
    return result

print(next_greater([4, 5, 2, 10, 8, 6, 12]))   # [5, 10, 10, 12, 12, 12, -1]

Where is it used?

The same pattern solves many interview and contest problems:

  • Daily temperatures: how many days until a warmer day.
  • Stock span: how many consecutive earlier days had a lower price.
  • Largest rectangle in a histogram and trapping rain water.
  • Flip the comparison to find the next smaller element.

Common mistakes

  • Storing values instead of indices. You need the index to write the answer in the right place.
  • Using <= when the problem asks for a strictly greater element, which changes how equal values behave.
  • Forgetting the elements left on the stack at the end. Their answer stays −1.
  • Scanning left to right for a “previous greater” problem. Flip the direction or the comparison to match the question.

Complexity at a glance

Case / operationTimeWhy
Whole arrayO(n)Each index is pushed once and popped at most once.
Brute force (compare every pair)O(n²)Shown for comparison.
Extra spaceO(n) for the stack

Quick check

Test yourself — pick an answer to see if you got it.

1. What does the stack store in the next-greater-element algorithm?

2. In what order are the values on the stack, from bottom to top?

3. Why is the total running time O(n) even though there is a while loop inside the for loop?

4. What is the answer for an element that is still on the stack at the end?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Monotonic Stack (Next Greater Element). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.