Find the Greater Element

One of the test cases is not passing. As it is mentioned that the array is circular so, first of all, we find the greater element for the last index, and for that, I have used a simple while loop till a next greater element is found or we reach the last index. and after that, I have used the concept of the stack to find greater elements for the rest of the array.

import java.util.*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner sc=new Scanner (System.in);
int n=sc.nextInt();

	int[] ar=new int[n];
	for (int i=0; i<n; i++) {
		ar[i]=sc.nextInt();
	}

	Stack<Integer> st=new Stack<>();

	int[] nextg=new int[n];
	int j=0;
	while (j<n-1 && ar[j]<ar[n-1]) {
		j++;
	}

	if (j==n-1) {
		nextg[n-1]=-1;
	} else {
		st.push(ar[j]);
		nextg[n-1]=ar[j];
	}
	

	st.push(ar[n-1]);

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

		while (st.size()>0 && st.peek()<=ar[i]) {
			st.pop();
		}

		if (st.size()==0) {
			nextg[i]=-1;
		} else {
			nextg[i]=st.peek();
		}
		st.push(ar[i]);
	}

	for (int i=0; i<n; i++) {

		System.out.print (nextg[i]+" ");
	}



}

}

for the input
5
5 5 5 5 5
the output should be
-1 -1 -1 -1 -1
debug for this

Thank you, I got where it is failing.

1 Like

please mark this as resolved :slight_smile: