Skip to main content

Next Greater Element II

Problem

Given a circular array (the next element of the last element is the first element of the array), return the next greater number for every element. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Example

Input: [1, 2, 1]

Output: [2, -1, 2]

Explanation:

The first 1's next greater number is 2;

The number 2 can't find a next greater number;

The second 1's next greater number needs to search circularly, which is also 2.

Solution

We still use a monotonic stack. For circular arrays, a useful trick is to use the modulo operation to simulate doubling the array length.

/**
* @param {number[]} nums
* @return {number[]}
*/
var nextGreaterElements = function (nums) {
const n = nums.length
const stack = []
const res = new Array(n).fill(-1)

for (let i = 0; i < n * 2 - 1; i++) {
while (stack.length !== 0 && nums[stack[stack.length - 1]] < nums[i % n]) {
res[stack.pop()] = nums[i % n]
}

stack.push(i % n)
}

return res
}