""" We traverse the array from right to left because the next greater element must lie on the right side. A stack is used to keep only useful candidates in decreasing order. For each element, we pop smaller/equal values until we find a greater one on top (or stack becomes empty). That top becomes the answer, then we push the current element for future elements on the left. """ class Solution: def nextLargerElement(self, arr): st=[arr[-1]] ans=[-1] for i in reversed(arr[:-1]): if st and st[-1]>i: ans.append(st[-1]) st.append(i) else: while len(st) and st[-1]<=i: st.pop() if len(st): ans.append(st[-1]) else: ans.append(-1) st.append(i) ans.reverse() return ans