This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu
key – in order to start in circular way ->
generally we iterate starting from i=0 , j = (i+1) but since this is circular
we iterate i=0 , j = (i+1) % nums.length
in order to move to next element generally we do j++ or j = j +1
but since this is circular the next element of j will be (j+1) % nums.length
/**
* @param {number[]} nums
* @return {number[]}
*/
var nextGreaterElements = function(nums) {
const n = nums.length;
const result = new Array(n).fill(-1)
for (let i = 0; i < nums.length; i++) {
let j = (i + 1) % nums.length; // Start from next index in a circular manner
while (j !== i) {
if (nums[j] > nums[i]) {
result[i] = nums[j];
break; // Break out of the loop once we find the next greater element
}
j = (j + 1) % nums.length; // Move to the next index in a circular manner
}
}
return result;
};
This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu