A simple approach is to iterate through each element of the array. For every element, first find its next greater element on the right, and then determine the next smaller element to the right of that greater element.
Output
2 2 -1 1 -1 -1 -1
Using Monotonic Stack - O(n) Time and O(1) Space
The idea is to first determine the next greater element (NGE) for every element in the array. This can be efficiently done using a stack, which helps process elements in linear time while keeping track of indices whose next greater element has not yet been found.
Once the next greater element indices are stored, we then compute the next smaller element (NSE) for each element in the array using a similar stack-based approach.
Finally, we combine both results: for each element, we take its next greater element, and then find the next smaller element of that greater element. If any step does not exist, we return -1. This combined information gives us the next smaller element of the next greater element for every array element.