Not able to understand how the logic of stack is working for this circular array part

if the input is 20 3 4 2 6 10 40 or 3 4 6 10 1 8 then the code is showing wrong output. I am not able to understand how it will keep record if for the last element of the array and in my test case 1 expected output
40 4 6 6 10 40 -1 but my code is showing something else


@jaiskid please look as I am not bale to understand your stack logic

Hello @piyush.bansal8158625,

This stack won’t work for circular part.
The code that you have written would print the largest element on the right of current element, considering it a non-circular array.


I have changed my code and all test cases passed.Thanks
But is there any other approach or this approach is also fine wrt to optimisation
the time is o(n) and space is also O(n).

Hey @piyush.bansal8158625,

Using stack is an optimal approach.
Please, mark this doubt as resolved.