Leetcode – 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 …


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Leetcode – Next Greater Element II." Rakesh Reddy Peddamallu | Sciencx - Sunday June 23, 2024, https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/
HARVARD
Rakesh Reddy Peddamallu | Sciencx Sunday June 23, 2024 » Leetcode – Next Greater Element II., viewed ,<https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/>
VANCOUVER
Rakesh Reddy Peddamallu | Sciencx - » Leetcode – Next Greater Element II. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/
CHICAGO
" » Leetcode – Next Greater Element II." Rakesh Reddy Peddamallu | Sciencx - Accessed . https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/
IEEE
" » Leetcode – Next Greater Element II." Rakesh Reddy Peddamallu | Sciencx [Online]. Available: https://www.scien.cx/2024/06/23/leetcode-next-greater-element-ii/. [Accessed: ]
rf:citation
» Leetcode – Next Greater Element II | Rakesh Reddy Peddamallu | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.