Next Greater Element II LeetCode solution in JavaScript

1
var nextGreaterElements = function (nums) {
2
const len = nums.length;
3
const ans = new Array(len).fill(-1);
4
const stack = [];
5
for (let i = 0; i < len; i++) {
6
if (i == 0) stack.push([i, nums[i]]);
7
else {
8
while (stack.length && stack.at(-1)[1] < nums[i]) {
9
ans[stack.pop()[0]] = nums[i];
10
}
11
stack.push([i, nums[i]]);
12
}
13
}
14
for (let num of nums) {
15
while (stack.length && stack.at(-1)[1] < num) {
16
ans[stack.pop()[0]] = num;
17
}
18
}
19
return ans;
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0