Find The Greater Element

import java . util . *;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
int [] a= new int[n];
for(int i=0;i<a.length;i++) {
a[i]=sc.nextInt();
}
Stack stack = new Stack<>(); // generic function
for (int i = 0; i < a.length; i++) {
while (!stack.isEmpty() && a[i] > stack.peek()) {
int rv = stack.pop();
System.out.print(a[i]+" ");
}
stack.push(i); // Corrected this line
}
while (!stack.isEmpty()) {
int rv = stack.pop();
System.out.print( "-1 ");
}
}
}

what’s wrong mistake i have done in this programme only one test are passing.

Hey @faizanali,

while (!stack.isEmpty() && a[i] > stack.peek()) {

Instead of this line it should be as you are adding the indexes in the stack and you need to compare them to the value at that index instead of the index.

while (!stack.isEmpty() && a[i] > a[stack.peek()] ) {

You’ve considered the array to be linear, but it is mentioned in the problem statement that the array is circular. So iterating over the elements just once won’t be able to solve our problem. In order to resolve this, try traversing over 2*n elements.

It’d be wise to store the result rather than just printing it is bound to give an error.

Consider the following testcase:
5
1 2 5 4 3

After the above modification, your code is giving the result as:
2 5 -1 -1 -1

But the actual result for this is:
2 5 -1 5 5

So try iterating the array twice and while simultaneously storing the result in an array.

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.