#include<bits/stdc++.h>
using namespace std;

int main(){
int n;
cin>>n;
int a[n];
stack<int> st;
vector<int> v;
for(int i=0;i<n;i++){
  cin>>a[i];
}

for (int i = n-1; i >=0 ; i--)
{
  if(st.size()==0){
  v.push_back(-1);
}else if(st.top()>a[i] && st.size()>0){
  v.push_back(st.top()); 
}else if(st.size()>0 && st.top()<a[i]){
  while(st.size()>0 && st.top()<a[i]){
    st.pop();
  }
  if(st.size()==0){
    v.push_back(-1);
  }else if(st.top()>a[i]){
    v.push_back(st.top());
  }
}
st.push(a[i]);
}

reverse(v.begin(),v.end());
for(int i=0;i<n;i++){
  cout<<v[i]<<" ";
}

return 0;
}



Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: