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
[4,2,4,-1,-1]
The 4 answers the first three; the 4 and the 3 have nothing larger to their right.

Example 2

Input
nums = [3, 2, 1]
Output
[-1,-1,-1]
Each value is smaller than the one before it, so none of them is ever answered.

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
Step through nextGreater([2, 1, 2, 4, 3]) call by call