**A tricky solution would be to use Binary Search Trees. We start scanning the array from right to left and insert each element into the BST. For each inserted element, we replace it in the array by its inorder successor in BST. If the element inserted is the maximum so far (i.e. its inorder successor doesn’t exists), we replace it by -1.**

```
class solution {
void insert(TreeNode*& root, int val, TreeNode*& succ) {
if(root == nullptr)
root = new TreeNode(val);
if (val < root->val) {
succ = root;
insert(root->left, val, succ);
}
else if (val > root->val)
insert(root-right, val, succ);
}
vector<int> replace(vector<int> a) {
int n = (int)a.size();
TreeNode* root = nullptr;
vector<int> result(n);
for (int i = n - 1; i >= 0; i--) {
TreeNode* succ = nullptr;
insert(root, a[i], succ);
if (succ)
result[i] = succ->val;
else
result[i] = -1;
}
return result;
}
};
```