Next Greater Element II
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #503
nums is circular (the element after the last is the first). For every element, return the next greater number traversing forward circularly, or −1 if none exists.
Examples
text
[1, 2, 1] → [2, −1, 2]
[1, 2, 3, 4, 3] → [2, 3, 4, −1, 4]Hints
- Simulate circularity by iterating indices 0…2n−1 and using
i mod n. - Only push indices during the first pass.
Approach
Use a stack of indices with decreasing values. Iterate i from 0 to 2n−1 with x = nums[i % n]: while the top's value is less than x, pop it and set its answer to x. Push indices only when i < n. The second lap lets elements near the end find greater values at the start. O(n).
Complexity
Time: O(n). Space: O(n).
Python solution
def nextGreaterElements(nums):
n = len(nums)
ans, st = [-1] * n, []
for i in range(2 * n):
x = nums[i % n]
while st and nums[st[-1]] < x:
ans[st.pop()] = x
if i < n:
st.append(i)
return ansJavaScript solution
function nextGreaterElements(nums) {
const n = nums.length, ans = new Array(n).fill(-1), st = [];
for (let i = 0; i < 2 * n; i++) {
const x = nums[i % n];
while (st.length && nums[st[st.length - 1]] < x) ans[st.pop()] = x;
if (i < n) st.push(i);
}
return ans;
}