Next Greater Element
Find the next greater element for each item using a Monotonic Stack.
4
-1
5
-1
2
-1
25
-1
Empty
Monotonic Stack (Indices)Status: Ready
Speed
Algorithm Logic
1function nextGreater(arr):
2 stack = [] // stores indices
3 result = [-1] * n
4
5 for i from 0 to n-1:
6 while stack and arr[stack.top] < arr[i]:
7 idx = stack.pop()
8 result[idx] = arr[i]
9 stack.push(i)