LeetCode 503 Next Greater Element II - Implementation

The approach

Iterate 2n times with modulo. Only push on first pass.

function nextGreaterElements(nums): n = len(nums) result = [-1] * n stack = [] for i in range(2 * n): while stack and nums[i % n] > nums[stack[-1]]: result[stack.pop()] = nums[i % n] if i < n: stack.push(i) return result

O(n)O(n) time, O(n)O(n) space.