Nearest Smaller Values
Explanation
Here, we are given an array and we need to find the closest value to it's left that is smaller than itself. We need to output it's position if it exists, otherwise output 0
.
This can be done using a stack and popping all the elements greater than or equal to the current element, and outputting the smaller element's index.
This is because the greater values to the left side of a value will never be used, hence they can popped.
Code
n = int(input())
arr = list(map(int, input().split()))
stack = []
ans = []
for i, e in enumerate(arr):
while stack and stack[-1][0] >= e:
stack.pop()
ans.append(0 if not stack else stack[-1][-1] + 1)
stack.append((e, i))
print(" ".join(str(e) for e in ans))