Next Greater Element Visualization & Animation

Finds the next greater element to the right for each array element using a monotonic decreasing stack; O(n).

## What is it? For each element in an array, find the next element to its right that is strictly greater than it. If no such element exists, the answer is -1. Solved efficiently using a monotonic stack. ## How it works - Use a stack that maintains a decreasing sequence of indices - For each element `arr[i]`: - While the stack is not empty and `arr[stack.top()] < arr[i]` → the current element is the "next greater" for the top; pop it and record the answer - Push `i` onto the stack - Any indices remaining on the stack after processing have no next greater element → answer is -1 ## When to use - Problems involving "next larger", "next smaller", "previous larger/smaller" elements - Building blocks for Daily Temperatures, Online Stock Span, Histogram problems ## Key Points - O(n) time — each element is pushed and popped at most once - O(n) space for the stack - A monotonic decreasing stack for "next greater"; a monotonic increasing stack for "next smaller"

Category: algorithms

Difficulty: intermediate

Time Complexity: O(n)

Space Complexity: O(n)

Next Greater Element

intermediate

Finds the next greater element to the right for each array element using a monotonic decreasing stack; O(n).

Init
empty
Monotonic Stack
i
4
[0]
5
[1]
2
[2]
10
[3]
8
[4]
NGE Result
?
[0]
?
[1]
?
[2]
?
[3]
?
[4]
Initialize: empty stack, all NGE = ? (unresolved).