Replace every element with the least greater element on its right - GeeksforGeeks
Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater element on right side, replace it with -1.
Read full article from Replace every element with the least greater element on its right - GeeksforGeeks
Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater element on right side, replace it with -1.
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.
/* A utility function to insert a new node with
given data in BST and find its successor */
void
insert(Node*& node,
int
data, Node*& succ)
{
/* If the tree is empty, return a new node */
if
(node == NULL)
node = newNode(data);
// If key is smaller than root's key, go to left
// subtree and set successor as current node
if
(data < node->data)
{
succ = node;
insert(node->left, data, succ);
}
// go to right subtree
else
if
(data > node->data)
insert(node->right, data, succ);
}
// Function to replace every element with the
// least greater element on its right
void
replace(
int
arr[],
int
n)
{
Node* root = NULL;
// start from right to left
for
(
int
i = n - 1; i >= 0; i--)
{
Node* succ = NULL;
// insert current element into BST and
// find its inorder successor
insert(root, arr[i], succ);
// replace element by its inorder
// successor in BST
if
(succ)
arr[i] = succ->data;
else
// No inorder successor
arr[i] = -1;
}
}