Next Greater Element II
Problem Link: https://leetcode.com/problems/next-greater-element-ii/
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
# Extend [1,2,1] to [1,2,1,1,2,1]
s=[]
ans=[]
n=len(nums)
s=[]
for i in range(n*2-1,-1,-1):
if(i<n):
if(len(s)==0):
ans.append(-1)
else:
if(s[-1]>nums[i]):
ans.append(s[-1])
else:
while(len(s)>0 and s[-1]<=nums[i]):
s.pop()
if(len(s)==0):
ans.append(-1)
else:
ans.append(s[-1])
s.append(nums[i])
# If i>=n
else:
s.append(nums[i%n])
return ans[::-1]
Last updated