Back to Problem
Official
2323 views
Editorial: Next Greater Element (Circular)
by admin ·
24
1 Intuition
Simulate the wrap-around by scanning the array twice.
2 Approach
Use a monotonic decreasing stack of indices over 2n steps, only pushing during the first pass.
3 Complexity Analysis
Time O(n), Space O(n).
4 Solution Code
class Solution:
def nextGreaterElements(self, nums: list[int]) -> list[int]:
n = len(nums)
out, stack = [-1] * n, []
for i in range(2 * n):
x = nums[i % n]
while stack and nums[stack[-1]] < x:
out[stack.pop()] = x
if i < n:
stack.append(i)
return out
5 Code Walkthrough
The reference solution below implements the approach step by step.