Doubt regarding Next Greater element problem

Where is the mistake in this code . I am getting TLE .
import java.util.*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner scan = new Scanner(System.in) ;
int n = scan.nextInt() ;
long[] arr = new long[n] ;

	for(int i = 0 ; i < n ; i ++){
		arr[i] = scan.nextLong() ;
	}

	nextGreater(arr) ;
}

public static void nextGreater(long[] arr){

	Stack<Long> stack = new Stack<Long>() ;

	for(int i = 0 ; i < arr.length ; i ++){

		while(!stack.isEmpty() && arr[i] >stack.peek()){
			stack.pop() ;
			System.out.print(arr[i]+" ") ;
		}

		stack.push(arr[i]) ;
	}

	// checking greater element for the last element in the array
	for(int i = 0 ; i <= arr.length-2 ; i ++){
		if(arr[i] >stack.peek()){
			stack.pop() ;
			System.out.print(arr[i]+" ") ;
		}
	}

	if(!stack.isEmpty()){
		while(!stack.isEmpty()){
			System.out.print(-1+" ") ;
		}
	}

}

}

Well, your logic seems correct to me. But you ain’t printing the answer in a correct order, store the answer for each index from 0 to n - 1 and print the entire array at the end. your code must be printing answers off order.

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.

@Lalit2142,

I see that you have submitted the correct code. What doubt are you having regarding the question?

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.