Algomination
Data Structures
AboutContact

Algomination

Learn algorithms and data structures through smooth, interactive visualizations.

SortingSearchingArray AlgorithmsData StructuresAboutContact

© 2026Algomination. Created by Omang Rawat & Rahul Soni.

Omang Rawat
Rahul Soni
All array algorithms

Next Greater Element

Time O(n)Space O(n)

For each element, finds the first larger value to its right using a monotonic stack of indices that are still waiting for their answer. Each index is pushed and popped at most once.

4
?
5
?
2
?
25
?
7
?
8
?
next greater element (row below each value)
Stack (top)
(bottom)
Keep a stack of indices still waiting for a greater element to their right.
Step 1 / 19

About Next Greater Element

For each element, finds the first larger value to its right using a monotonic stack of indices that are still waiting for their answer. Each index is pushed and popped at most once.

Time complexity: O(n). Space complexity: O(n).

How it works, step by step

Core idea — Keep a stack of indices whose next-greater element hasn't been found yet, ordered so their values decrease from bottom to top.

What each pass accomplishes — When a new value is larger than the value on top of the stack, it is that index's next greater element — pop and record it, repeating until the top is bigger. Then push the new index. Every index enters and leaves the stack once, giving O(n).

Use the interactive visualizer above to run Next Greater Element on your own input and watch every comparison, swap, and operation animate step by step — pause, scrub, or replay at any speed.