Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
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 1:
Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
var nextGreaterElements = function (nums) {
// as it is circular array doubling the length of array
let nArray = nums.concat(nums);
// orignal array
let n = nums.length;
// dummy result array;
let result = new Array(n).fill(-1);
// temp arrray to hold values
let stack = [];
// looping till twice of array so that all element gets a fair chance to check for it next greater
for (let i = 0; i < nArray.length; i++) {
// doing mod so that we have index(s) always equal to lengtho of num
// here playing with index(s) hence nums[stack[0]] ===> will give value
while (stack.length && nums[i % n] > nums[stack[stack.length - 1]]) {
result[stack.pop()] = nums[i % n];
}
stack.push(i % n);
}
return result;
};
console.log(nextGreaterElements([1, 2, 1]));
Top comments (0)