Next Greater Element II

Problem Id: 503 Difficulty: Medium


Intuition

Solution


class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        ans = [-1] * len(nums)
        stack = []
        for i in range(len(nums) * 2):
            i = i % len(nums)
            while stack and nums[stack[-1]] < nums[i]:
                ans[stack.pop()] = nums[i]
            stack.append(i)
        return ans