Leetcode 503 Solution

This article provides solution to leetcode question 503 (next-greater-element-ii)

https://leetcode.com/problems/next-greater-element-ii

Solution

class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: a = nums + nums
s = [] ans = [] for j in range(len(a) - 1, -1, -1): while s and a[j] >= s[-1]: s.pop()
ans.append(s[-1] if s else -1)
s.append(a[j])
ans = list(reversed(ans)) return ans[:len(nums)]