SDE & MLE Prep

503. Next Greater Element II

Problem

nums is circular (after the last element comes the first). For every element return the first greater value found by walking forward around the circle, or −1 if none exists.

Example: [1,2,1] → [2,-1,2]

Constraints: n ≤ 10⁴.

Circular array → iterate 2n indices using i % n; only push during the first pass.

Complexity: O(n).

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