![]() |
VOOZH | about |
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.
Input: arr[] = [2, 6, 9, 1, 3, 2]
Output: [3, 9, -1, 2, -1, -1]
Explanation: The least next greater element of 2 is 3. The least next greater element of 6 is 9.least next greater element for 9 does not exist and so on.Input: arr[] = [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]
Explanation: The least next greater element of 8 is 18. The least next greater element of 58 is 63 and so on.
Table of Content
For every element, check all elements to its right and find the smallest element greater than it. For each index, we scan the remaining array and track the minimum value that satisfies the condition. If no such element exists, we keep
-1.
-1 if no such element exists The idea is to traverse the array from right to left while maintaining a sorted set of elements seen so far. For each element, we find the smallest element greater than it in O(Log n) time. Since the set is always sorted, this gives the required least greater element efficiently without scanning all elements on the right.
18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1
The idea is to transform the problem into a “next greater index” problem. We store elements along with their indices and sort them by value. Then, using a stack, we find the next greater index for each element. Since sorting ensures we process smaller elements first, the next valid index we assign will correspond to the least greater element on the right.
-1 if none exists18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1