Problem statement

https://binarysearch.com/problems/Circular-Greater-Element-to-the-Right/

Solution

Equal to Leetcode 0503 Next Greater Element II.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, nums):
        stack, n = [], len(nums)
        result = [-1]*n
        
        for i, num in enumerate(nums + nums[:-1]):
            while stack and stack[-1][1] < num:
                a, b = stack.pop()
                result[a%n] = num
            stack.append((i, num))
        
        return result