DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on

Leetcode - 503. Next Greater Element II

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

*Sample working *->

suppose when i goes to 3 , as j = i+1 ie 4 it crossed the end incase of nums = [1,2,1] , (i+1) % 4 ie 4 % 4 gives 0 , so it starts from index 0 instead of going to index 4

Learning

we can fill array of size n with -1 using new Array(n).fill(-1);

we can use break statements in for loops to exit out of loop

continue statement will skip one iteration

/**
 * @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;
};
Enter fullscreen mode Exit fullscreen mode

Please do follow the series if you are struggling with leetcode questions 😇

Top comments (0)