Not able to understand the tutorial also?

We are given a circular array, print the next greater number for every element. If it is not found print -1 for that number. To find the next greater number for element Ai , start from index i + 1 and go uptil the last index after which we start looking for the greater number from the starting index of the array since array is circular.

Input Format
First line contains the length of the array n. Second line contains the n space separated integers.

Constraints
1 <= n <= 10^6
-10^8 <= Ai <= 10^8 , 0<= i< n

Output Format
Print n space separated integers each representing the next greater element.

Sample Input
3
1 2 3
Sample Output
2 3 -1
Explanation
Next greater element for 1 is 2,
for 2 is 3 but not present for 3 therefore -1

hi himanshu,
Can you please share the link of tutorial.

@Jun18ELX0057

vector<int> nextGreaterElements(vector<int> &nums)
{
    int n = nums.size();
    vector<int> res(n);

    stack<int> s;

    for (int i = 2 * n - 1; i >= 0; i--)
    {

        while (!s.empty() && nums[s.top()] <= nums[i % n])
        {
            s.pop();
        }

        res[i % n] = (s.empty() ? -1 : nums[s.top()]);
        s.push(i % n);
    }

    return res;
}

hi himanshu,
Sorry for the late reply.
vector nextGreaterElements(vector &nums)

{

int n = nums.size();

vector<int> res(n);

stack<int> s;



// 2*n loop because we will have to go to start again from the end

// as it is a cirular array.

for (int i = 2 * n - 1; i >= 0; i--)                   

{

    while (!s.empty() && nums[s.top()] <= nums[i % n])

    {

        s.pop();

    }

    res[i % n] = (s.empty() ? -1 : nums[s.top()]);

    //Here we are storing the value of array if stack is not empty 

    // and if it is empty then -1.

    

    s.push(i % n);

    //In this we are pushing the index by doing mod with n because:-

    // lets say our array size is 5 and we have reached at 6th index that means

    // we have to go to index 1 of our array

    // Hence 6%5 is 1

    

}

return res;

}
I have added comments in this code but if you still have any doubt or not able to understand then please let me know, we will discuss over this a meet call.