![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to find for each array position (1-based indexing) the nearest position to its left having a smaller value.
Examples:
Input: N = 8, arr[] = {2, 5, 1, 4, 8, 3, 2, 5}
Output: 0 1 0 3 4 3 3 7
Explanation:
- For 1st element 2, there is no smaller element on the left, therefore print 0.
- For 2nd element 5, the 1st element = 2 is the smaller element on the left, therefore print 1.
- For 3rd element 1, there is no smaller element on the left, therefore print 0.
- For 4th element 4, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 5th element 8, the 4th element = 4 is the smaller element on the left, therefore print 4.
- For 6th element 3, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 7th element 2, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 8th element 5, the 7th element = 2 is the smaller element on the left, therefore print 3.
Input: N = 5, arr[] = {1, 2, 3, 2, 1}
Output: 0 1 2 1 0
Explanation:
- For 1st element 1, there is no smaller element on the left, therefore print 0.
- For 2nd element 2, the 1st element = 1 is the smaller element on the left, therefore print 1.
- For 3rd element 3, the 2nd element = 2 is the smaller element on the left, therefore print 2.
- For 4th element 2, the 1st element = 1 is the smaller element on the left, therefore print 1.
- For 5th element 1, there is no smaller element on the left, therefore print 0.
Approach: To solve the problem, follow the below idea:
The problem can be solved using a Monotonic Stack to store the indices of elements of arr[]. Monotonic Stack stores all the elements in a certain order(increasing or decreasing). We will use Monotonic Stack such that it stores indices and as we move from top to bottom, we have indices of decreasing elements. Iterate over the array arr[] and for each item, keep popping the indices from the top of our stack as long as value at index = top is greater than or equal to our current item. This is because any value greater than our current value won’t be the answer for any future items, since our current item is smaller and is located further to the right in the array.
If we find a position such that value at that position is less than our current item, we’ll set the answer for our current position to this position. This is because our stack keeps the most recently added (rightmost) items at the top, so this position will be the rightmost position with a value less than our current item.
Finally, we’ll add the current position to the stack.
Step-by-step algorithm:
Below is the implementation of the algorithm:
0 1 0 3 4 3 3 7
Time Complexity: O(N), where N is the size of arr[].
Auxiliary Space: O(N)