Given an array of distinct integers, replace every element with the least greater element on its right or with -1 if there are no greater elements.

For example,

Input:  { 10, 100, 93, 32, 35, 65, 80, 90, 94, 6 }
 
Output: { 32, -1, 94, 35, 65, 80, 90, 94, -1, -1 }

Practice this problem

A simple solution is to check if every array element has a successor to its right or not by using nested loops. The outer loop picks elements from left to right of the array, and the inner loop searches for the smallest element greater than the picked element and replaces the picked element with it. Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

32 -1 94 35 65 80 90 94 -1 -1

Java


Download  Run Code

Output:

[32, -1, 94, 35, 65, 80, 90, 94, -1, -1]

Python


Download  Run Code

Output:

[32, -1, 94, 35, 65, 80, 90, 94, -1, -1]

The time complexity of the above solution would be O(n2), where n is the size of the input.

 
Another solution is to use a BST. The idea is to traverse the array from right to left and insert each element into the BST. Replace each array element by its inorder successor in the BST or by -1 if its inorder successor doesn’t exist.

Following is the C, Java, and Python implementation based on the above idea. This solution work only for distinct integers.

C


Download  Run Code

Output:

32 -1 94 35 65 80 90 94 -1 -1

C++


Download  Run Code

Output:

32 -1 94 35 65 80 90 94 -1 -1

Java


Download  Run Code

Output:

[32, -1, 94, 35, 65, 80, 90, 94, -1, -1]

Python


Download  Run Code

Output:

[32, -1, 94, 35, 65, 80, 90, 94, -1, -1]

The time complexity of the above solution remains O(n2), but it can be reduced to O(n.log(n)) using height-balanced trees. The worst case happens when the input array is sorted in either ascending or descending order.

 
Author: Aditya Goel