Given an array arr, for each element find the next greater element to its right — the first element further right that is strictly greater. If there is none, use -1.
Return an array of these next-greater values, one per position.
<= the current element; the remaining top is its next greater.Input: arr = [1, 3, 2, 4] Output: [3, 4, 4, -1] Next greater to the right of 1 is 3; of 3 is 4; of 2 is 4; of 4 there is none (-1).
Input: arr = [6, 8, 0, 1, 3] Output: [8, -1, 1, 3, -1] 8 has no greater element to its right, and neither does the last 3.
- 1 <= arr.length <= 10^6 - 1 <= arr[i] <= 10^9
For each element you want the first strictly-greater element to its right. Scanning rightward every time is O(n²) and redoes work. A monotonic decreasing stack, swept right to left, reuses those comparisons: it holds exactly the elements that could still be some earlier element's answer, so the answer is always sitting right on top.
“Strictly greater or greater-or-equal?”
Strictly greater — an equal value is not a valid next-greater.
“What if nothing to the right is greater?”
The answer for that position is -1.
For each element I need the first strictly greater element to its right.
I sweep right to left with a stack that stays decreasing, popping anything at most as large as the current element.
Whatever remains on top is the next greater element; then I push the current value.
Worked example — arr = [1, 3, 2, 4]
i=3 (4): stack empty -> res[3]=-1; push 4 -> [4] i=2 (2): top 4 > 2 -> res[2]=4; push 2 -> [4,2] i=1 (3): pop 2 (<=3) -> top 4 > 3 -> res[1]=4; push 3 -> [4,3] i=0 (1): top 3 > 1 -> res[0]=3; push 1 -> [4,3,1] answer: [3, 4, 4, -1]
If arr[i] is at least as large as a stacked value, that value can never be the next-greater of anything to the left of i — arr[i] blocks it. So pop it.
After popping the <= arr[i] elements and pushing arr[i], the stack remains decreasing bottom-to-top, so its top is always the nearest greater element to the right.
A value is pushed exactly once and popped at most once, making the total work O(n) despite the inner while-loop.
| Scan right each time | Monotonic stack | |
|---|---|---|
| Idea | For each i, scan right for the first greater | Sweep right-to-left, keep a decreasing stack |
| Time | O(n^2) | O(n) |
| Space | O(1) | O(n) |
The brute rescans overlapping suffixes; the stack keeps only the candidates that can still be an answer. Full code is in the Approaches selector below.
Key takeaway
Sweep right to left with a decreasing stack. For each element, pop everything <= it; the remaining top (or -1) is its next-greater element; then push it. Amortized O(n).
res = [-1] * n; stack = []
for i from n-1 down to 0:
while stack and stack.top <= arr[i]: pop
res[i] = stack.top if stack else -1
push arr[i]
return res