Next greater element
Medium TimeO(n) SpaceO(n)
Given an array nums, return an array holding, for each element, the first value to its right that is strictly greater than it, and -1 where there is none. The search never wraps around, an equal value does not answer, and the result has one entry per input element, in the same order.
Examples
Example 1
- Input
- nums = [2, 1, 2, 4, 3]
- Output
- The 4 answers the first three; the 4 and the 3 have nothing larger to their right.
[4,2,4,-1,-1]
Example 2
- Input
- nums = [3, 2, 1]
- Output
- Each value is smaller than the one before it, so none of them is ever answered.
[-1,-1,-1]
The Code
function nextGreater(nums) {
const result = new Array(nums.length).fill(-1);
const stack = [];
for (let i = 0; i < nums.length; i++) {
while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {
const idx = stack.pop();
result[idx] = nums[i];
}
stack.push(i);
}
return result;
}
nextGreater([2, 1, 2, 4, 3]);Done
More like this
All stacks & queues examples (8) →- Valid parentheses Push every opener; every closer must match the top.
- Evaluate RPN Numbers go on the stack; an operator eats the top two.
- Daily temperatures How many days until it gets warmer — same stack, distance instead.
- Min stack Carry the minimum alongside each value so getMin is O(1).
- Queue from stacks Two LIFO stacks make one FIFO queue — reversal cancels out.
- Largest rectangle A bar’s rectangle ends where a shorter bar appears on either side.