#include <stack>
#include <vector>
class NextElement {
  public:
    vector<int> findNext(vector<int> A, int n) {
        // write code here
        stack<int >stk;
        vector<int> res(n, -1);
        for (int i = n - 1; i >= 0; --i) {
            stack<int> tmp;
            while (!stk.empty() && stk.top() <= A[i] ) {
                tmp.push(stk.top());
                stk.pop();
            }
            if (!stk.empty()) res[i] = stk.top();
            stk.push(A[i]);
            while (!tmp.empty()) {
                stk.push(tmp.top());
                tmp.pop();
            
            }
        }
        return res;
    }
};