503. Next Greater Element II
Asked at 17Amazon55Bloomberg51Microsoft46Google45Meta41Apple22KLA69Sigmoid87ServiceNow55Morgan Stanley54Zoho52Flipkart52Nvidia39Visa39tcs27TikTok26Goldman Sachs21
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
assert Solution().nextGreaterElements([1, 2, 1]) == [2, -1, 2]
assert Solution().nextGreaterElements([1, 2, 3, 4, 3]) == [2, 3, 4, -1, 4]
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < 2 * n; i++) {
int x = nums[i % n];
while (!st.isEmpty() && nums[st.peek()] < x) res[st.pop()] = x;
if (i < n) st.push(i);
}
return res;
}
}
func nextGreaterElements(nums []int) []int {
n := len(nums)
res, st := make([]int, n), []int{}
for i := range res {
res[i] = -1
}
for i := 0; i < 2*n; i++ { // two passes handle the wrap-around
x := nums[i%n]
for len(st) > 0 && nums[st[len(st)-1]] < x {
res[st[len(st)-1]] = x
st = st[:len(st)-1]
}
if i < n {
st = append(st, i)
}
}
return res
}