#K46792. Closest Greater Element on the Right
Closest Greater Element on the Right
Closest Greater Element on the Right
Given an array of integers of size \(N\), for each element, find the closest greater element to its right. In other words, for each index \(i\) find the smallest index \(j\) (where \(j > i\)) such that \(a_j > a_i\). If no such element exists, output \(-1\) for that position.
Example:
Input: 4 4 5 2 10 Output: 5 10 10 -1
Note: The problem must be solved using efficient algorithms. A common approach is to use a monotonic stack which can achieve \(O(N)\) time complexity.
inputFormat
The first line contains an integer \(N\) representing the number of elements in the array. The second line contains \(N\) space-separated integers representing the elements of the array.
outputFormat
Output a single line containing \(N\) space-separated integers, where the \(i\)th integer is the closest greater element to the right of the \(i\)th element in the input array. If no such element exists, output \(-1\) in its place.
## sample4
4 5 2 10
5 10 10 -1
</p>