I am using Monotonic Stack for finding previous greater indexes for the elements in the list arr. I want to return a list with all the indexes that shows indexes of previous greater element. But for any input , I am getting output as arr = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]. What is one thing that I am missing in the below code?
class Solution(object):
def previousGreaterIndex(self,arr):
stack = []
previous_greater = [-1]*len(arr) # create an aray to store elements
for i in range(len(arr)):
while stack and arr[stack[-1]] <= arr[i]:
stack_top = stack.pop()
if stack:
previous_greater[stack_top] = i
stack.append(i)
return previous_greater
if __name__ == '__main__':
arr = [13, 8, 1, 5, 2, 5, 9, 7, 6, 12]
print(Solution().previousGreaterIndex(arr))
i even tried to tweak <= to < to change the monotonic stack to non-increasing but not getting the required result.