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
![](https://www.radiofree.org/wp-content/plugins/print-app/icon.jpg)
Rakesh Reddy Peddamallu | Sciencx (2024-06-23T15:39:51+00:00) Leetcode – Next Greater Element II. Retrieved from https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.