Time-Limit error

I have used the queue approach.
But I am facing time-limit error.
Please look into the code.

Hi @mananaroramail,
Please save the code on ide.codingblocks.com and share the url as a reply.

Your first while loop inside the for loop will go in a infinite loop as “i” is the same and is not incrementing.Also if i increments the logic is not correct.This is a circular array that means if there are no greater element to the right then you should start the starting index which is 0. Therefore queue approach will not work in this case.

Try using stacks .It has a two line code if you use stack and the prime part of learning is to apply correct data structure that makes work easier and in less time.

How can I approach for a circular array using stacks. I got the correct answer by using n*n loop. Also in this ide I am not able to use the stack class which I just copy and paste here. I declared it private .

Use inbuilt stack function …Stack will make your solution work in O(n).If you do not want to use it that is your choice. It is a two line approach so it just about using stack to store the index in a particular way.

Can you provide me with the approach as I am able to put the elements in the stack if it were to be linear and not circular.
I tried solving it by taking indexes as remainders ( as we do in queues ) but then too I had to go for a n*n loop.

See telling the approach will be same as letting you know the solution but as you have already submitted here is the approach …Hope you will understand how they used stacks and if you do not i will suggest to do dry run on paper with pen .
while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % nums.length]) {
stack.pop();
}

        res[i % nums.length] = (stack.isEmpty() ? -1 : nums[stack.peek()]);
        stack.push(i % nums.length);
1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.