imashutosh51

Next greater element

Feb 14th, 2026
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. """
  2. We traverse the array from right to left because the next greater element must lie on the right side.
  3. A stack is used to keep only useful candidates in decreasing order.
  4. For each element, we pop smaller/equal values until we find a greater one on top (or stack becomes empty).
  5. That top becomes the answer, then we push the current element for future elements on the left.
  6. """
  7.  
  8. class Solution:
  9.     def nextLargerElement(self, arr):
  10.         st=[arr[-1]]
  11.         ans=[-1]
  12.         for i in reversed(arr[:-1]):
  13.             if st and st[-1]>i:
  14.                 ans.append(st[-1])
  15.                 st.append(i)
  16.             else:
  17.                 while len(st) and st[-1]<=i:
  18.                     st.pop()
  19.                 if len(st):
  20.                     ans.append(st[-1])
  21.                 else:
  22.                     ans.append(-1)
  23.                 st.append(i)
  24.         ans.reverse()
  25.         return ans
  26.        
Advertisement
Add Comment
Please, Sign In to add comment