import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone{
	public static void main (String[] args) throws java.lang.Exception{
		int[] arr = {6,3,1,8,2,9,7};
		Stack<Integer> st1 = new Stack<Integer>();
		Stack<Integer> st2 = new Stack<Integer>();
		List<Integer> result = new ArrayList<>();
		
		for(int i=arr.length-1;i>=0;--i){
		    while(!st1.isEmpty() && arr[(int)st1.peek()] < arr[i]){
		    	st2.push(st1.pop());
		    }
		    
			if(st2.isEmpty()) result.add(-1);
			else result.add(arr[(int)st2.peek()]);
			
			while(!st2.isEmpty()) st1.push(st2.pop());
			
			if(st1.isEmpty() || arr[(int)st1.peek()] > arr[i]){
				st1.push(i);
			}
		}
		
		Collections.reverse(result);
		System.out.println(Arrays.toString(arr));
		System.out.println(result.toString());
	}
}