Related Articles

# Replace every element with the least greater element on its right

• Difficulty Level : Hard
• Last Updated : 06 May, 2021

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 elements on the right side, replace it with -1.

Examples:

```Input: [8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28]
Output: [18, 63, 80, 25, 32, 43, 80, 93,
80, 25, 93, -1, 28, -1, -1]```

A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the smallest element greater than the picked element on its right side. Finally, the outer loop will replace the picked element with the element found by inner loop. The time complexity of this method will be O(n2).

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 exist), we replace it by -1.

Below is the implementation of the above idea –

## C++

 `// C++ program to replace every element with the``// least greater element on its right``#include ``using` `namespace` `std;` `// A binary Tree node``struct` `Node {``    ``int` `data;``    ``Node *left, *right;``};` `// A utility function to create a new BST node``Node* newNode(``int` `item)``{``    ``Node* temp = ``new` `Node;``    ``temp->data = item;``    ``temp->left = temp->right = NULL;` `    ``return` `temp;``}` `/* A utility function to insert a new node with``   ``given data in BST and find its successor */``Node* insert(Node* node, ``int` `data, Node*& succ)``{``    ` `    ``/* If the tree is empty, return a new node */``    ``if` `(node == NULL)``        ``return` `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;``        ``node->left = insert(node->left, data, succ);``    ``}` `    ``// go to right subtree``    ``else` `if` `(data > node->data)``        ``node->right = insert(node->right, data, succ);``    ``return` `node;``}` `// 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``        ``root = 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;``    ``}``}` `// Driver Program to test above functions``int` `main()``{``    ``int` `arr[] = { 8,  58, 71, 18, 31, 32, 63, 92,``                  ``43, 3,  91, 93, 25, 80, 28 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``replace(arr, n);` `    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << arr[i] << ``" "``;` `    ``return` `0;``}`

## Java

 `// Java program to replace every element with``// the least greater element on its right``import` `java.io.*;` `class` `BinarySearchTree{``    ` `// A binary Tree node``class` `Node``{``    ``int` `data;``    ``Node left, right;` `    ``Node(``int` `d)``    ``{``        ``data = d;``        ``left = right = ``null``;``    ``}``}` `// Root of BST``static` `Node root;``static` `Node succ;` `// Constructor``BinarySearchTree()``{``    ``root = ``null``;``    ``succ = ``null``;``}` `// A utility function to insert a new node with``// given data in BST and find its successor``Node insert(Node node, ``int` `data)``{``    ` `    ``// If the tree is empty, return a new node``    ``if` `(node == ``null``)``    ``{``        ``node = ``new` `Node(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;``        ``node.left = insert(node.left, data);``    ``}` `    ``// Go to right subtree``    ``else` `if` `(data > node.data)``        ``node.right = insert(node.right, data);``        ` `    ``return` `node;``}` `// Function to replace every element with the``// least greater element on its right``static` `void` `replace(``int` `arr[], ``int` `n)``{``    ``BinarySearchTree tree = ``new` `BinarySearchTree();` `    ``// start from right to left``    ``for``(``int` `i = n - ``1``; i >= ``0``; i--)``    ``{``        ``succ = ``null``;``        ` `        ``// Insert current element into BST and``        ``// find its inorder successor``        ``root = tree.insert(root, arr[i]);` `        ``// Replace element by its inorder``        ``// successor in BST``        ``if` `(succ != ``null``)``            ``arr[i] = succ.data;``            ` `        ``// No inorder successor``        ``else``            ``arr[i] = -``1``;``    ``}``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = ``new` `int``[] { ``8``, ``58``, ``71``, ``18``, ``31``,``                            ``32``, ``63``, ``92``, ``43``, ``3``,``                            ``91``, ``93``, ``25``, ``80``, ``28` `};``    ``int` `n = arr.length;` `    ``replace(arr, n);` `    ``for``(``int` `i = ``0``; i < n; i++)``        ``System.out.print(arr[i] + ``" "``);``}``}` `// The code is contributed by Tushar Bansal`

## Python3

 `# Python3 program to replace every element``# with the least greater element on its right` `# A binary Tree node``class` `Node:``    ` `    ``def` `__init__(``self``, d):``        ` `        ``self``.data ``=` `d``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# A utility function to insert a new node with``# given data in BST and find its successor``def` `insert(node, data):``    ` `    ``global` `succ``    ` `    ``# If the tree is empty, return a new node``    ``root ``=` `node` `    ``if` `(node ``=``=` `None``):``        ``return` `Node(data)` `    ``# If key is smaller than root's key, go to left``    ``# subtree and set successor as current node``    ``if` `(data < node.data):``        ` `        ``#print("1")``        ``succ ``=` `node``        ``root.left ``=` `insert(node.left, data)` `    ``# Go to right subtree``    ``elif` `(data > node.data):``        ``root.right ``=` `insert(node.right, data)``        ` `    ``return` `root` `# Function to replace every element with the``# least greater element on its right``def` `replace(arr, n):``    ` `    ``global` `succ``    ``root ``=` `None` `    ``# Start from right to left``    ``for` `i ``in` `range``(n ``-` `1``, ``-``1``, ``-``1``):``        ``succ ``=` `None` `        ``# Insert current element into BST and``        ``# find its inorder successor``        ``root ``=` `insert(root, arr[i])` `        ``# Replace element by its inorder``        ``# successor in BST``        ``if` `(succ):``            ``arr[i] ``=` `succ.data``        ` `        ``# No inorder successor``        ``else``:  ``            ``arr[i] ``=` `-``1``            ` `    ``return` `arr` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``arr ``=` `[ ``8``, ``58``, ``71``, ``18``, ``31``, ``32``, ``63``,``            ``92``, ``43``, ``3``, ``91``, ``93``, ``25``, ``80``, ``28` `]``    ``n ``=` `len``(arr)``    ``succ ``=` `None` `    ``arr ``=` `replace(arr, n)` `    ``print``(``*``arr)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to replace every element with``// the least greater element on its right``using` `System;` `class` `BinarySearchTree{``    ` `// A binary Tree node``public` `class` `Node``{``    ``public` `int` `data;``    ``public` `Node left, right;``    ` `    ``public` `Node(``int` `d)``    ``{``        ``data = d;``        ``left = right = ``null``;``    ``}``}` `// Root of BST``public` `static` `Node root;``public` `static` `Node succ;` `// Constructor``public` `BinarySearchTree()``{``    ``root = ``null``;``    ``succ = ``null``;``}` `// A utility function to insert a new node with``// given data in BST and find its successor``public` `static` `Node insert(Node node, ``int` `data)``{``    ` `    ``// If the tree is empty, return a new node``    ``if` `(node == ``null``)``    ``{``        ``node = ``new` `Node(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;``        ``node.left = insert(node.left, data);``    ``}``    ` `    ``// Go to right subtree``    ``else` `if` `(data > node.data)``    ``{``        ``node.right = insert(node.right, data);``    ``}``    ``return` `node;``}` `// Function to replace every element with the``// least greater element on its right``public` `static` `void` `replace(``int``[] arr, ``int` `n)``{``    ``//BinarySearchTree tree = new BinarySearchTree();``    ``// Start from right to left``    ``for``(``int` `i = n - 1; i >= 0; i--)``    ``{``        ``succ = ``null``;``        ` `        ``// Insert current element into BST and``        ``// find its inorder successor``        ``root = BinarySearchTree.insert(root, arr[i]);``        ` `        ``// Replace element by its inorder``        ``// successor in BST``        ``if` `(succ != ``null``)``        ``{``            ``arr[i] = succ.data;``        ``}``        ` `        ``// No inorder successor``        ``else``        ``{``            ``arr[i] = -1;``        ``}``    ``}``}` `// Driver code``static` `public` `void` `Main()``{``    ``int``[] arr = { 8, 58, 71, 18, 31,``                  ``32, 63, 92, 43, 3,``                  ``91, 93, 25, 80, 28 };``    ``int` `n = arr.Length;``    ` `    ``replace(arr, n);``    ` `    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``Console.Write(arr[i]+``" "``);``    ``}``}``}` `// This code is contributed by rag2127`

## Javascript

 ``

Output:

`18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1`

The worst-case time complexity of the above solution is also O(n2) as it uses BST. The worst-case will happen when array is sorted in ascending or descending order. The complexity can easily be reduced to O(nlogn) by using balanced trees like red-black trees.